Instantiating once in an update
I have seen a lot of examples using a boolean to only instantiate once in update and I have followed the examples but it's not working for me. I'm probably missing something here, please help me find it.
using UnityEngine;
using System.Collections;
public class FurnitureManagerScript : MonoBehaviour
{
public GameObject gameobjecttoplace;
public RaycastHit hit;
public bool click;
// Use this for initialization
void Start()
{
click = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0) && click==false && gameobjecttoplace!=null)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out hit);
click = true;
spawnatclick();
}
}
void spawnatclick()
{
if (click == true && hit.transform.tag == "BuildableArea")
{
click = false;
Instantiate(gameobjecttoplace, Camera.main.ScreenToWorldPoint(Input.mousePosition), Quaternion.identity);
Debug.Log(click);
}
}
}
I am trying to let the player select a button which stores what gameobject the player wants to place in an area and then instantiate it once. However, right now it is spawning based on frame rate so I'm getting like a lot of gameobjects.
Answer by meat5000 · May 06, 2016 at 11:20 AM
Use
Input.GetMouseButtonDown(0) //You only want 1 click!
Use
hit.point //Spawn at the Raycasted position instead of at the camera
using UnityEngine;
using System.Collections;
public class FurnitureManagerScript : MonoBehaviour
{
public GameObject gameobjecttoplace;
public RaycastHit hit;
public bool click;
void Start()
{
click = false;
}
void Update()
{
if (Input.GetMouseButtonDown(0) && click==false && gameobjecttoplace!=null)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out hit);
click = true;
spawnatclick();
}
}
void spawnatclick()
{
if (click == true && hit.transform.tag == "BuildableArea")
{
click = false;
Instantiate(gameobjecttoplace, hit.point, Quaternion.identity);
}
}
}
Also, when writing your scripts use the tab key to do your spacing ins$$anonymous$$d of adding whitespace with spacebar.
Your answer
Follow this Question
Related Questions
Why does Bool code never work in my C# Script? 1 Answer
List of Structs variable values not changing 1 Answer
Spawning a prefab at a specific point in a procedurally generated map 1 Answer
How To Generate Platforms Down Each other in a pattern with some different positions Unity 1 Answer
How Do I Instantiate Multiple Coins Once The Enemy Dies? 1 Answer