Im trying to instantiate objects with a key press in a certain area. But when I play it and press L nothing happens.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawndirt : MonoBehaviour {
public GameObject dirtprefab;
public Vector3 center;
public Vector3 size;
// Use this for initialization
void Start () {
SpawnDirt ();
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.L))
SpawnDirt ();
}
public void SpawnDirt()
{
Vector3 pos = center + new Vector3(Random.Range(-size.x /2, size.x /2), Random.Range(-size.y /2, size.y /2),Random.Range(-size.z /2, size.z /2));
Instantiate (dirtprefab, pos, Quaternion.identity);
}
void OnDrawGizmoSelected()
{
Gizmos.color = new Color (1, 0, 0.5f);
Gizmos.DrawCube (transform.localPosition + center, size);
}
}
Does SpawnDirt work in your Start? Is the dirtprefab set to the proper prefab? Input.GetKey is for when you’re holding down the key between frames, are you holding it down or just quickly pressing it?
yes the first one does spawn, yes, I’ve tried both just in case and it still isnt working
Put in some Debug.Log messages when you check for keypress and when you are instantiating the prefab, and figure out if it is a problem detecting the keypress or in instantiating the prefab.
I got it to work, but how do I get them to spawn from the place were I want them to be
when I add transform.position it stops working
What does “stops working” mean? Does the rest of the method not get executed at all? If that is the case then you would have something like a null reference error in your console log, if so what is it?
once I add transfrom.position it doesnt allow me to spawn objects (the first one still spawns at start) and I dont get any errors or messages
I’ve fixed it, thanks for your help