- Home /
 
How to put a reference on a prefab through the script ?
Hello,
I pick the same example as this tutorial : Unity - GetComponent
On difference, I add a List<>.
 public class AsecondaryScript : MonoBehaviour
 {
     public int maVariable = 120;
 
     public List<string> testList = new List<string>();
 
     void Start ()
     {
         testList.Add ("Objet A 1");
         testList.Add ("Objet A 2");
         testList.Add ("Objet A 3");
     }
 }
 
               I link this script on a GameObject named : Pair1-1
Next, I put this script on another GameObject named : Pair1-2
 public class AmainScript : MonoBehaviour
 {
     public GameObject otherGameObject;
 
     private AsecondaryScript anotherScript;
 
     void Awake()
     {
         anotherScript = otherGameObject.GetComponent<AsecondaryScript> ();
     }
 
     IEnumerator Start ()
     {
         yield return new WaitForEndOfFrame ();
 
         Debug.Log ("Result 1 : " + anotherScript.maVariable);
         Debug.Log ("Result 2 : " + anotherScript.testList);
         Debug.Log ("Result 3 : ");
 
         foreach(String m in anotherScript.testList)
         {
             Debug.Log( "->" + m);
         }
     }
 }
 
               And finally, I put the reference GameObject Pair1-1 in "OtherGameObject" and it work.
The problem is, if both of my GameObject are Prefabs and are not put in the interface, I can't refer Pair1-1 to Pair1-2.
I need to do it with script.
But how could I do this ?
Answer by salex100m · Mar 18, 2015 at 12:34 AM
when the prefab is Instantiated, it is "awoken" so you can do this (attach the apple to one gameobject, and the banana to another) :
 using UnityEngine;
 using System.Collections;
 
 public class AppleScript : MonoBehaviour {
 
 
     public GameObject theGOwithBanana;
 
     void Awake(){
         theGOwithBanana = GameObject.Find ("GameObject1");
         
     }
 
 }
 
 
 using UnityEngine;
 using System.Collections;
 
 public class BananaScript : MonoBehaviour {
     
     
     public GameObject theGOwithApple;
     
     void Awake(){
         theGOwithApple = GameObject.Find ("GameObject2");
         
     }
     
 
               If the game object already exists in the game (not instantiated at run time), this will also work. Also, don't use "Find" anywhere other than Awake/Start.
Your answer