Spawn an object when player is near and presses button
I have a spawn point that I would like to spawn an object from when the player is within a certain distance and presses the appropriate button. How would I go about this?
At the moment I just have the object spawning at Start:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectSpawner : MonoBehaviour { public GameObject DefenseShield; public Transform Spawner; private void Start() { Instantiate(DefenseShield, Spawner.position, Spawner.rotation); } }
Thanks
Answer by Vencarii · Feb 26, 2018 at 10:29 AM
I would add Colliders to both the player and the spawn point. Set the player collider to "Is Trigger" and then on the spawn point you can use the OnTriggerEnter() (or OnTriggerEnter2D() for a 2D application) method to detect a collision and spawn the object.
Something like this (not tested, just out of my mind):
public voin OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Player") {
if (Input.GetKeyDown(KeyCode.X)){
// Instantiate here
}
}
}
Ops my bad, this won't work. There may be a better solution, but this one should work:
public class ObjectSpawner : $$anonymous$$onoBehaviour
{
public bool IsSpawnable = false;
public void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Player") {
IsSpawnable = true;
}
}
public void OnTriggerExit2D (Collider2D other)
{
if (other.tag == "Player") {
IsSpawnable = false;
}
}
public void Update()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.X)) {
if (IsSpawnable) {
// Instantiate here
}
}
}
}
Works like a charm. Thanks.
Here is full code for anyone else:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectSpawner : $$anonymous$$onoBehaviour {
public GameObject DefenseShield;
public Transform Spawner;
public bool IsSpawnable = false;
public void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
IsSpawnable = true;
}
}
public void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player")
{
IsSpawnable = false;
}
}
public void Update()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.LeftAlt))
{
if (IsSpawnable)
{
Instantiate(DefenseShield, Spawner.position, Spawner.rotation);
}
}
}
}