How to assign Instantiated object through script?
Hello. I have a script called "DestroyGameObject_10s". So that's what I have right now:
## DestroyGameObject_10s.cs ##
public GameObject road;
public GameObject myCar;
void Start () {
myCar = GameObject.Find("car");
road = RoadSpawn.road; // THIS DOESN'T WORK
}
And the other script called "RoadSpawn.cs"
void SpawnRoad(){
spawnedRoad = (GameObject)Instantiate(road, new Vector3(startRoadX + roadXCoordinates, road.transform.position.y, road.transform.position.z), Quaternion.Euler(0,0,0));
spawnedRoad.AddComponent<DestroyGameObject_10s>();
roadXCoordinates += 12;
}
So I want this Instantiated object called spawnedRoad to assign through script. But it doesn't work. Why?
I used RoadSpawn.road; I used RoadSpawn r = new RoadSpawn(); r.road;
But it doesn't work :( Thanks in advance.
Comment
Answer by UnityCoach · Apr 19, 2017 at 12:32 PM
AddComponent returns the component it added. So :
DestroyGameObject_10s dgo = spawnedRoad.AddComponent<DestroyGameObject_10s>();
dgo.road = theRoad; // replace with your reference
dgo.myCar = theCar; // replace with your reference
No. I have already found the solution. I've just added :
myCar = GameObject.Find("car");
road = gameObject;
Because script was attached to road object.