- Home /
Simple Instantiate/Spawning Example
I'm new to Unity3d I'm trying to learn the basics. Basically I'm trying something simple. When my character collides with a Cube it spawns a rock next to it.
This is my Script.
var Rock : Transform;
function OnCollisionEnter (collision : Collider) {
if(collision.gameObject.tag == "Player"){
Debug.Log("yay");
Instantiate (Rock);
}
}
I have attached this script to the Cube.. I'm getting nothing in the console, nothing is spawning. No errors.
I believe I got this code from one of manual I just change the prefab. Could someone help me out?
Edit I am getting a error
Script error: OnCollisionEnter This message parameter has to be of type: Collision The message will be ignored.
um am I missing something?
Answer by FLASHDENMARK · Jun 12, 2011 at 07:12 PM
The Instantiate function needs 3 variables:
What object you want to Instantiate.
Where it needs to be Instantiated.
The rotation of the Instantiated object.
And it needs to be Collision in the OnCollisionEnter field not Collider.
var Rock : Transform;
function OnCollisionEnter (collision : Collision)
{
if(collision.gameObject.tag == "Player")
{
Debug.Log("yay");
Instantiate (Rock, where I want it, what rotation it needs);
}
}
Right, and since, as you said, the first variable is a gameObject you should change Transform to GameObject ;)
You don't have to add anything to Instantiate aside from the prefab. "Instantiate (Rock);" is fine.
You're right (http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html) it still needs to be fed an object though, not a transform.
@Joshua: Transform is an object. Read the first example in link you just posted. :)
Answer by Chris D · Jun 12, 2011 at 07:10 PM
OnCollisionEnter passes a collision, not a collider, try changing
function OnCollisionEnter (collision : Collider) {
to
function OnCollisionEnter (collision : Collision) {
Also, in your instantiate, you have to provide more details. Check out the overview on it here: http://unity3d.com/support/documentation/ScriptReference/index.Instantiate.html
You don't have to add anything to Instantiate aside from the prefab. "Instantiate (Rock);" is fine.
good call; I should really read to the bottom of the reference pages :(
Answer by Eric5h5 · Jun 12, 2011 at 08:01 PM
As the error says, you need to use Collision for the type (and not Collider). By the way, it's better to use CompareTag:
if (collision.CompareTag ("Player")) {
Your answer
Follow this Question
Related Questions
Networking: Object is instantiated twice instead of once 1 Answer
Spawn Point Problems 1 Answer
Code based 3d multiple cube instantiation 1 Answer
Instantiate over time? 1 Answer
Instantiated Object Spawning in different position 2 Answers