Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

C# reference gameObject from script not attached

Discussion in 'Scripting' started by fulbaio, May 20, 2014.

  1. fulbaio

    fulbaio

    Joined:
    May 20, 2014
    Posts:
    1
    Hi, I'm new to unity and I'm trying to populate an array of GameObject in a script not attached to an empty gameObject where I've stored some prefabs.

    \\\scriptA attached to objA
    public class objComp : MonoBehaviour {
    public GameObject objectA;
    public GameObject objectB;
    public GameObject objectC;
    public GameObject objectD;
    }

    In the inspector I've filled the slot of the public GameObject

    objectA -> prefabsObjA
    objectB -> prefabsObjB
    objectC -> prefabsObjC
    objectD -> prefabsObjD

    \\\scriptB attached to objB
    public class attachId : MonoBehaviour {

    private GameObject[] arrayPrefabs;

    scriptA scriptAscript;

    void Start () {

    arrayPrefabs = new GameObject[4];

    scriptAscript = gameObject.GetComponent<scriptA> ();

    arrayPrefabs [0] = scriptAscript.objectA as GameObject;
    arrayPrefabs [1] = scriptAscript.objectB as GameObject;
    arrayPrefabs [2] = scriptAscript.objectC as GameObject;
    arrayPrefabs [3] = scriptAscript.objectD as GameObject;

    }

    }
    and where I try to populate the array I receive the error: NullReferenceException: Object reference not set to an instance of an scriptB.Start ()

    Can someone give me some advice ? Thanks in advance.
     
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    The reason of it is that scriptA variable is not initialised.
    If scriptA is not inherited from MonoBehavior class you can initialize it directly with new keyword.
    Code (csharp):
    1.  
    2. scriptA scriptAscript = new scriptA ();
    3.  
     
  3. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    ScriptA is a monobehavior though, so just make sure it is added as a component to the same object as script B.
    Edit: or so it seems - I thought scriptA and objComp were the same script at first. ScriptA definitely needs to be instantiated in some manner.

    Also please use codetags when you write code :)

    http://forum.unity3d.com/threads/143875-Using-code-tags-properly
     
    Last edited: May 20, 2014