- Home /
how do I make it so my building prefab instantiates only once
I'm trying to make something where when a button is pressed a building prefab is instantiated and appears in a position on a globe. I only want 1 building to be spawned and no more. i kind of know what i need to do but I'm not sure how to put it into code as i am a beginner and just learning as i go.
here is the script i am using to instantiate the buildings
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public Transform[] spawnLocations;
public GameObject[] WhatToSpawnPrefab;
public GameObject[] WhatToSpawnClone;
public void Update()
{
SpawnBuilding();
void SpawnBuilding()
{
if (Input.GetKeyDown("1"))
{
GameObject go = Instantiate(WhatToSpawnPrefab[0], spawnLocations[0].transform.position, Quaternion.Euler(85, 90, 360)) as GameObject;
go.transform.parent = GameObject.Find("Globe").transform;
}
}
}
}
any help would be greatly appreciated!
Answer by Ak0rn · Jul 10, 2019 at 10:51 AM
could have a bool called alreadyInstantiated or something and then change your code to this: if (Input.GetKeyDown("1") && !alreadyInstantiated) { alreadyInstantiated = true; GameObject go = Instantiate(WhatToSpawnPrefab[0], spawnLocations[0].transform.position, Quaternion.Euler(85, 90, 360)) as GameObject; go.transform.parent = GameObject.Find("Globe").transform; } else {alreadyInstantiated = false;}
its spawning each time i press the button to spawn the building, i only want there to be one on the globe
sorry that's me being stupid, get rid of the "else" part. That should fix it. If not I'll take a closer look in a $$anonymous$$ute
Answer by ertunaozderya · Jul 10, 2019 at 10:54 AM
i am beginner too but you can try to write your codes into start method.
I don't think he wants it to spawn automatically, I think he wants it to only spawn when the player presses a button
Your answer
Follow this Question
Related Questions
[SOLVED]: Bullets passing through platforms - Brackeys Tutorial 1 Answer
How to instantiate a sprite after it has been destroyed? 2 Answers
Instantiate not working? 0 Answers
why do my instantiated prefabs spawn depending on the position / rotation of the globe? 1 Answer
How to make an Array equal the Components of an Instantiated GameObject 1 Answer