- Home /
How do I access variables from a game object from an instantiated prefab
I have a power up on my game, that when it is activated it instantiates a few of a prefab that I made. When the prefabs collide with an object I want points to be added to the player's score. I have tried all kinds of stuff to get the script on the instantiated prefabs to interact with the script that I have on an empty gameobject called GameControl that holds all the score info, but nothing is working for me. I think this is the closest I have gotten to getting the end result that I want. This script is on my prefab and is attempting to edit the TotalCount variable on my empty game object.
void Start()
{
GameObject.Find("GameControl").GetComponent<PointCounterScript>();
GameObject PointCounter = GameObject.Find("GameControl");
Component OverallPoints = PointCounter.GetComponent<PointCounterScript>();
}
void OnTriggerEnter(Collider Other)
{
if(Other.gameObject.tag == "Person")
{
OverallPoints.TotalCount = OverallPoints.TotalCount + 1;
}
}
}
I get two error messages when I try to run this. They are both "error CS0103: The name `OverallPoints' does not exist in the current context". One error for each "OverallPoints" I used on line 23. Any ideas on what I am doing wrong? Or suggestions for a better way to accomplish this? I am new to C#, so I apologize in advance if it is something obvious!
I didnt fully understand your problem.As far as I understoor,the error you are getting because of a typemismatch i guess.try changing this line
Component OverallPoints = PointCounter.GetComponent();
to this
PointCounterScript OverallPoints = PointCounter.GetComponent<PointCounterScript>();
Answer by DajBuzi · Jul 24, 2014 at 11:18 AM
You have declared variable in the Start method and tried to use it in the OnTriggerEnter method. Rewrite the code and put Component OverallPonts on top of the class and then you can access it in other methods ;)
Thanks! I kept the code the same and moved both of the lines with the GameObject and Component to the top of the class. And I think it worked. But now I get this error message " error CS0236: A field initializer cannot reference the nonstatic field, method, or property `StampedeUnicornScript.PointCounter'"
It is on the line with the
Component OverallPoints = PointCounter.GetComponent<PointCounterScript>();
Do you know what that is about?