- Home /
 
Button to summon prefab
I need a button that I created on a canvas to summon one of my prefabs on screen. I'm doing a tower defense game in C# and I have no idea what I;m doing....i need this answered in like 2 or 3 days..
This isn't really a question, you are kind of demanding a script. That's not what Q&A is for... Also, you have to understand, the moderation queue becomes massive very quickly, we're 3 days behind on all questions at the moment, and we do our best to keep things moving.
I was going to reject this, but I can help you out a little... Still you need to actually learn C# and Unity and ask questions that pertain to problems, or learning, not a demand for a script...
Attach this to your UI button, and drag and drop the spawn location object into the Spawn Location slot of the script, and the Prefab you want to spawn into the Prefab slot.
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 public class SpawnPrefab : $$anonymous$$onoBehaviour
 {
     public GameObject prefab;
     public GameObject spawnLocation;
     void Awake()
     {
         Button button = GetComponent<Button>();
         if (button)
         {
             button.onClick.AddListener(Spawn);
         }
     }
     void Spawn()
     {
         Instantiate(prefab, spawnLocation.transform.position, spawnLocation.transform.rotation);
     }
 }
 
                 Answer by Skaster87 · May 24, 2017 at 07:41 AM
Hi,
You need to add an on click event to the button that runs your instantiate function.
So you'll create the button in the canvas, and in the inspector find the On Click () box and press the + at the bottom. Add the game object that contains the script with the function, then select the script component and function from the drop down menu and it should work.
So you'll need to create a GameObject with a script attached that contains a call to instantiate or reuse the object from the pool. Let me know if you need specific examples.
Brackeys does a great Tower Defense tutorial that covers this topic. Specifically episodes 12 and 17 https://m.youtube.com/playlist?list=PLPV2KyIb3jR4u5jX8za5iU1cqnQPmbzG0
Your answer
 
             Follow this Question
Related Questions
How do I make buttons that turn into a text field? 2 Answers
assign keyboard buttons 1 Answer
Problem making buttons from array of array 1 Answer
Random Button / Plane Generation. 0 Answers