how to make the GameObject have a parameter in unity (c#)?

1.7k views Asked by At

please help me how to get the value of "currentPeople.timeCount;" for example i have a script:

public class BuildingPlacement : MonoBehaviour 
{
    public GameObject currentPeople;public int DelayTime;private int timeCount;
}

if i want to say that

DelayTime = currentPeople.timeCount;

i try this code below and it says nullreferenceexception object reference not set to an instance of an object:

DelayTime = (BuildingPlacement)currentPeople.GetComponent(typeof(BuildingPlacement).timeCount);

How do I get the value of currentPeople.timeCount ? is it possible?

1

There are 1 answers

2
Programmer On BEST ANSWER

You can't add a variable to a GameObject as mentioned in your original question. It is very likely you want to add the script to the GameObject which also makes the timeCount variable available to that GameObject.

If that's the case then select the currentPeople GameObject and drag the BuildingPlacement script to it in the Editor. This is called attaching script to a GameObject. You can also do this via code with:

currentPeople.AddComponent<BuildingPlacement>();

To access the timeCount variable that is in the BuildingPlacement script which is attached to the currentPeople GameObject:

 int value =  currentPeople.GetComponent<BuildingPlacement>().timeCount;

It seems like you are lacking the basic knowledge of Unity. You can start from here.