Problem with random tranform using array

Problem is in this line:

Target = target [targetIndex];

The compiler complains with:

Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Transfrom'

This is the script:

using UnityEngine;
using System.Collections;
[System.Serializable]
public class projectile2 : MonoBehaviour {

	GameObject[] target;


	//	private float firingAngle = 45.0f;
	public float gravity = 900f;
	public Transform Projectile; 
	private Transform myTransform;
	public float Xlimit = -180f;
	private GameObject target1;
	void Awake()
	{
		myTransform = transform;  

	}


	void Start()


	{          
//		target = GameObject.FindGameObjectsWithTag ("point");

		StartCoroutine(SimulateProjectile());

	}


	IEnumerator SimulateProjectile()
	{
Transform Target;

target = new Transform[6];
		target [1] = GameObject.Find ("Target 1").transform.position;
		target [2] = GameObject.Find ("Target 2").transform.position;
		target [3] = GameObject.Find ("Target 3").transform.position;
		target [4] = GameObject.Find ("Target 4").transform.position;
		target [5] = GameObject.Find ("Target 5").transform.position;
		target [6] = GameObject.Find ("Target 6").transform.position;

int targetIndex = Random.Range (0, target.Length);

Target = target [targetIndex];

First of all you declared your target array as:

GameObject[] target;

So it’s an array of gameobjects. Inside your SimulateProjectile() method you try to assign a Transform array to the variable. That’s not possible an array of apples can’t be assigned to an array of oranges.

Next thing is all those lines:

target [1] = GameObject.Find ("Target 1").transform.position;

don’t make much sense. You try to assign the position of that object (which is a Vector3 value) to an element of your target array. No matter if your target array is of type GameObject[] or Transform[] this won’t work.

Next thing is your array seems to be ment to hold 6 items since you create it like this: new Transform[6];. However arrays start counting at “0”. So the highest index for an array with 6 elements is “5”. So you have the indices: (0, 1, 2, 3, 4, 5) which are 6 indices.

Some minor problems here are:

  • Since your “target” variable is an array it actually represents multiple objects. You should give it a plural name like targets.
  • Your script / code doesn’t seem to be complete. Keep in mind that your Target variable is declared inside the “SimulateProjectile” method, so it can only be used inside that method.

Things you might want to change:

  • GameObject arrays are quite useless. It’s better to use a Transform array. So i would suggest you change your GameObject[] target; to Transform[] targets;
  • When you assign your different targets you should assign their transform objects to the array element and not the position of the transforms and start counting at “0” : targets[0] = GameObject.Find ("Target 1").transform;

Target = target [targetIndex].transform;