Change the speed of cars from another script

Hi, my problem is Im trying to change the speed of the prefab cars from the instantiation game object.

public class enemyCarMoveOpp : MonoBehaviour {
	//this script attached to 3 cars

	public float speed = 2f;
	public float destroyTime = 8f;
	public GameObject carSpawn;

	// Use this for initialization
	void Start () {

		Destroy (gameObject, destroyTime);
	}

	// Update is called once per frame
	void Update () {


		transform.Translate (new Vector3 (0, 1, 0) * speed * Time.deltaTime);

	}
}

and this is the script from instantiation

public class carSpawner : Spawner {


	// Use this for initialization
	void Start () {

		InvokeRepeating ("spawnCar", delayTimer, delayTimer);

	}


	// Update is called once per frame
	void Update () {

	}

	public void spawnCar () 
	{
		carPos = new Vector3(carTrackLine, transform.position.y, transform.position.z); 
		int objectIndex = Random.Range (0, carSpawn.Length);
		Instantiate (carSpawn [objectIndex], carPos, Quaternion.identity);
                
                 //this is what I did but its not working
		GameObject.Find ("Car").GetComponent<enemyCarMove> ().speed += 10f;


	}


}

One more question, can I add more then one speed in array then let it generate randomly ?
and thanks :slight_smile:

Lesson about instantiation: Every instantiated object have (Clone) notification added to the end of object’s name.

Script tries to find “Car” but instantiated is called “Car(Clone)”.

For “object searching” try tags instead of name because one set tag will never be changed.

Then use “GameObject.FindGameObjectWithTag” function.

public void spawnCar () 
     {
         carPos = new Vector3(carTrackLine, transform.position.y, transform.position.z); 
         int objectIndex = Random.Range (0, carSpawn.Length);

         GameObject newCar = Instantiate (carSpawn [objectIndex], carPos, Quaternion.identity) as GameObject;
                 
         enemyCarMove [] newCars = GameObject.FindGameObjectsWithTag ("Car").GetComponent<enemyCarMove> ();

         foreach (enemyCarMove car in newCars)
         {
            car.speed += 10f;
         }
 
 
     }

Sorry, my mistake. Try this code with foreach loop. It should work. Notice there is “FindGameObjectsWithTag” name.