UNITY - public value null after assigning it from a different script

by Addy Pete   Last Updated August 10, 2018 13:13 PM

Hello I am a beginner in Unity and still currently exploring with scripts. So I ran into a problem.

In FetchAndAssign.cs Script

    void Start(){

         GameObject theEdge = GameObject.Find("Edge2");
         StallComponentAdder edge = theEdge.GetComponent<StallComponentAdder>();
         edge._id = _id;

    }

In StallComponentAdder.cs Script where it is attached to Edge2 GameObject

    public string _id;

    void Start () {
         string storeID = _id;
         print(storeID);
    }

When I try to print the storeID it won't print anything, why is that so?



Answers 1


The problem you’re running into is likely due to an incorrect script execution order. The Start method on all scripts wither the same priority which are loaded at the same time are executed in an arbitrary order. Your FetchAndAssign.Start is probably running afterStallComponentAdder.Start.

You can address this by either adjusting the script execution order to ensure that StallComponentAdder is run later, or you could change Start inside of FetchAndAssign to use ‘Awakeinstead, which runs beforeStart`.

Ed Marty
Ed Marty
August 10, 2018 13:06 PM

Related Questions


Unity - C# - Overlapping Rectangles not separating

Updated March 26, 2015 07:26 AM


Unable to instantiate objects Straight in unity

Updated April 04, 2015 15:05 PM


How to find nearest gameobject on one side

Updated June 25, 2016 08:05 AM