- Home /
Add instantiate object to GameObject[]
Hello,
I'm pretty new to using arrays.. I am creating object clones and trying to store them into array called colors.. I've googled and looked up for some answers but with no luck. :( Those are the codes I got from internet..
public var colors : GameObject[];
var startPoint: Vector3;
var endPoint: Vector3;
var numObjects: int;
var objects: Transform[];
function addToArray ( obj : GameObject )
{
colors += [obj];
}
function Start ()
{
for ( var s = 0 ; s < numObjects; s++ )
{
var newObj = Instantiate(objects[ Random.Range( 0 , objects.Length ) ] );
newObj.position = Vector3.Lerp( startPoint , endPoint, ( s * 1.0 ) / ( numObjects - 1 ) );
addToArray( newObj );
}
}
... But it gives me error when I try adding the object to array..
Player.js(49,35): BCE0017: The best overload for the method 'Player.addToArray(UnityEngine.GameObject)' is not compatible with the argument list '(UnityEngine.Transform)'.
Could anyone please fix this problem and explain what I did wrong? Thank you in advance.
Answer by fafase · Jul 29, 2013 at 08:41 PM
var newObj = Instantiate(objects[ Random.Range( 0 , objects.Length ) ] );
addToArray(newObj.gameObject);
Answer by abeldantas · Jul 29, 2013 at 08:36 PM
var newObj : GameObject = Instantiate(objects[ Random.Range( 0 , objects.Length ) ] ) as GameObject;
newObj.transform.position = Vector3.Lerp( startPoint , endPoint, ( s * 1.0 ) / ( numObjects - 1 ) );
addToArray( newObj );
Seems that by default Instantiate returns a transform, not a GameObject.
By default,I think Instantiate returns an object. In UnityScript it gets casted automatically to the type of the prefab, in this case Transform. In C#, you have to explicitly cast it.
Gets casted to the type of the prefab automagically? Hm, nice.
How do you know type of your prefab? I thought a prefab was just a reusable GameObject. Are you saying that he created a prefab of type Transform?
@abeldantas, the prefab is indeed of type Transform since objects is of type Transform. So UnityScript converts to the type, not magically though, it just cast to the type it found. C# does not do that for instance and requires the programmer to manually cast to the type.
That is one of the bonus of C#, nothing happens without you doing it. UnityScript does a lot on the background and then you get surprise.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Randomly instantiate objects from array without choosing the same item twice. 2 Answers
Remeber the value between frame Update() 1 Answer
How can i delete an item from an array after being used? (So, it won't be repeated) 2 Answers
Array problem? help please! 1 Answer