I have instantiated an object in a scene and now I need to assign another object in a script of that instantiated object …How to do this?
First you need to find that other script, using GetComponent(). Then you need to access the public GameObject variable which you must have in your script, setting it to the GameObject you want to assign.
Say your script within the instantiated object is called “DoAThing” and within it you have a variable:
public class DoAThing : MonoBehaviour {
public GameObject target;
// etc.
void Start() {
}
//...
}
Now within your script that instantiates an object holding the DoAThing script, you will have written
GameObject instantiatedObject = Instantiate(myPrefab) as GameObject;
or similar. Now add to this:
DoAThing myScript = instantiatedObject.GetComponent<DoAThing>();
myScript.target = myTargetObject;
where myTargetObject is the GameObject you need applied to the script.
(If you won’t ever need to change anything else about your script, you could shorten this to
instantiatedObject.GetComponent<DoAThing>().target = myTargetObject;
Well, since there aren’t any examples, lets assume there is some script that gets it’s typical Unity Behaviour methods called, like Awake and Start.
If it’s not important to do it during Awake and could be called each time this gameobject is enabled/disabled then start would be the best place. You need to know the script names that you want to adjust or change values on that are attached to this newly instantiated gameobject.
// gameobject base script
using UnityEngine;
using System.Collections;
public class MyGameObjectScript: MonoBehaviour
{
void Start()
{
// first find the script using GetComponent
MyOtherScriptType myscript = GetComponent<MyOtherScriptType>();
// with a reference, set your variable, this must be accessible and not private
myscript.MyGameObject = transform; // pretend the MyGameObject is of type Transform
}
}
// The other attached script
using UnityEngine;
using System.Collections;
public class MyOtherScriptType : MonoBehaviour
{
public Transform MyGameObject;
void Update()
{
// do stuff
}
}
UnityScript/Javascript version
// gameobject base script MyGameObjectScript.js
function Start()
{
// first find the script using GetComponent
MyOtherScriptType myscript = GetComponent.<MyOtherScriptType>();
// with a reference, set your variable, this must be accessible and not private
myscript.MyGameObject = transform; // pretend the MyGameObject is of type Transform
}
// The other attached script MyOtherScriptType.js
public var MyGameObject:Transform;
function Update()
{
// do stuff
}