2

I want to place six objects(ball) on scene. I think the code look workable but I receive a console message. The message :

"Assets/GameScripts/Instance.cs(26,40): error CS0266: Cannot implicitly convert type object' toUnityEngine.Vector3'. An explicit conversion exists (are you missing a cast?)"

using UnityEngine; using System.Collections;

public class Instance : MonoBehaviour { public GameObject ball;

public ArrayList coordinateContainer = new ArrayList();



// Use this for initialization
void Start () {

    coordinateContainer.Add(new Vector3(1f,1f,1f));
    coordinateContainer.Add(new Vector3(2f,1f,1f));
    coordinateContainer.Add(new Vector3(3f,1f,1f));
    coordinateContainer.Add(new Vector3(4f,1f,1f));
    coordinateContainer.Add(new Vector3(5f,1f,1f));
    coordinateContainer.Add(new Vector3(6f,1f,1f));


    //ball.transform.position = new Vector3(1f,1f,1f);
    ball.transform.rotation = Quaternion.identity;

    for (int i = 0; i <  6; i++) {
        ball.transform.position = coordinateContainer[i];
        Instantiate(ball,ball.transform.position,ball.transform.rotation);
    }
}

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

}

}

1 Answer 1

5

Since you're using an ArrayList the vectors are being stored as objects. Try this

ball.transform.position = (Vector3)coordinateContainer[i];

You may be better off with List<Vector3> instead of an ArrayList so that you can avoid the casting (as List<T> can only hold objects of type T).

Sign up to request clarification or add additional context in comments.

4 Comments

'Assets/GameScripts/Instance.cs(26,74): error CS0077: The as' operator cannot be used with a non-nullable value type UnityEngine.Vector3'' - I receive that message when I try "as Vector3".
@HalilCosgun - I've updated the answer to use direct casting. This is another good reason to use a List<T> because you're looping through all the objects in the coordinateContainer and if it can't be cast to a Vector3 object then an exception will be thrown.
Thanks a lot. :) It works. Thanks for advice, I will use List.
@HalilCosgun - You're welcome. Depending on how often it's called you may also notice a speed improvement with a List because Vector3 is a value type which means it has to be boxed and unboxed when stored and retrieved in an ArrayList. With a List, you avoid the boxing/unboxing performance hit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.