- Home /
Errors with Random Instantiate Script(Solved)
I'm trying to make a simple script to randomly pick one of 3 game objects (prefabs) and instantiate the chosen one adjacent to the object the script is attached.
using UnityEngine;
using System.Collections;
public class SpawnNextSection : MonoBehaviour
{
public Transform[] nextSection;
void OnTriggerEnter(Collider other)
{
int randomSection = Random.Range(0,nextSection.Length);
if (other.tag == "Player")
{
Vector3 spawnPosition = transform.position + new Vector3 (0, 0, 4);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (randomSection, spawnPosition, spawnRotation);
}
}
}
unfortunately I'm getting some errors -
Assets/Procedural/SpawnNextSection.cs(17,25): error CS1502: The best overloaded method match for UnityEngine.Object.Instantiate(UnityEngine.Object, UnityEngine.Vector3, UnityEngine.Quaternion)' has some invalid arguments. and Assets/Procedural/SpawnNextSection.cs(17,25): error CS1503: Argument
#1' cannot convert int' expression to type
UnityEngine.Object'
A little help here would be greatly appreciated guys
???
Answer by _met44 · Mar 24, 2015 at 02:46 PM
You're passing "randomSection" as the first parameter of Instantiate() which expects a unity Object.
I believe you meant to write:
Instantiate (nextSection[randomSection], spawnPosition, spawnRotation);
Actually, Random.Range has been recently modified
http://docs.unity3d.com/ScriptReference/Random.Range.html "Returns a random integer number between $$anonymous$$ [inclusive] and max [exclusive] (Read Only)."
so nextSection.Length - 1
is not required.
Oh I had missed that, good to know thanks mate !
I wish i could +1 you for the tip.
I'll edit my post to correct this.
Answer by ParanoidSnail · Mar 24, 2015 at 03:53 PM
Should be simple
Replace: Instantiate (randomSection, spawnPosition, spawnRotation);
with
Instantiate (nextSection[randomSection], spawnPosition, spawnRotation);
Your answer
Follow this Question
Related Questions
instantiate gameobject[] 1 Answer
Randomizing a selection from an array 1 Answer
Random.Range doesn't work 1 Answer