Home > front end >  How would I edit an attribute of a component of a game object within Unity through a C# file?
How would I edit an attribute of a component of a game object within Unity through a C# file?

Time:06-16

I'm trying to make a script that will dynamically change the near clip plane's distance based on how close the camera is to "nodes" that I place down. The only issue is that I am not sure how to refer to the near clip plane field on the camera component in the C# script in order to change it during runtime. Image of the camera component for reference.

Also, here is the script so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NodeManager : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

    List<Transform> nodeArray = new List<Transform>;
    var parentNode = transform;

    Transform[] children = GetComponentsOnChildren<Transform>();

    foreach (Transform child in children)
    {

        nodeArray.Add(child);

    }

    List<float> distanceMagnitudes = new List<float>;

}

// Update is called once per frame
void Update()
{
    
    for(var i = 0; i < parentNode.childCount; i  )
    {

        Vector3 offset = nodeArray[i].position - this.position;

        distanceMagnitudes[i] = offset.sqrMagnitude;


    }

    float distanceToClosest = sqrt(distanceMagnitudes.min());

    if(distanceToClosest < 10)
    {

        parentNode.Find("Camera Offset").Find("Main Camera").


    }

}

}

CodePudding user response:

First of all try not to use Find("Main Camera") to get camera in your scene instead define the camera before and set it's value in the Start() method like this or make it public and set it in the inspector

Camera mainCamera;

private void Start()
{
    // find by type if you will only have one camera always
    mainCamera = FindObjectOfType<Camera>();
    
    // find by tag if you might have several cameras
    mainCamera = GameObject.FindWithTag("Your Camera Tag").GetComponent<Camera>();
}

You can get the near clip wherever by..

mainCamera.nearClipPlane = 1.0f;  //Your Value
  • Related