- Home /
spawn object on keypress c#
Hello, I'm trying to spawn an object in front of the player when pressing on 'X' I'm very new to c# and don't now how to do this could anyone help me with this?
Heres some code that may or may not work, not tested -
using System.Collections;
using UnityEngine;
public class SpawnOBJ : $$anonymous$$onoBehaviour {
public Vector3 ObjectSpawnPosition;
public GameObject obj;
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.X)) {
Instantiate(obj, ObjectSpawnPosition, Quaternion.identity) as Transform;
}
}
Assets/Resources/NewScripts/spawnmedc.cs(9,6): error CS1519: Unexpected symbol `if' in class, struct, or interface member declaration
does not work...
using System.Collections;
using UnityEngine;
public class SpawnOBJ : $$anonymous$$onoBehaviour {
public Vector3 ObjectSpawnPosition;
public GameObject obj;
void Update(){
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.X)) {
Instantiate(obj, ObjectSpawnPosition, Quaternion.identity) as Transform;
}
}
}
That should fix it.
Tags like "help..." and all variants thereof are USELESS on a site devoted to giving people help. Put a little more thought into your tags so those that come later find relevant information.
Answer by The Kracken · Dec 02, 2013 at 09:31 PM
if(Input.GetKeyDown(KeyCode.X)) {
Instantiate(obj, ObjectSpawnPosition, Quaternion.identity);
}
Try That.
Thanks! it does spawn only, I have to add the coords now, is there a way to spawn it in front of the player?
The ObjectSpawnPosition should be where you want it to spawn. one way to do it is to create an empty GameObject and parent it to your player. then position it where you want it to spawn and then drag it into the inspector.
Another soulution would be
ObjectSpawnPosition = Player.transform.position + (Player.transform.forward * distance);
where distance is how far in front of the player you want it to spawn.