Last Updated on 2021-10-28 by Clay
In the process of making the game with Unity, we cannot manually place all game objects we need. In other words, sometimes we need to automatically generate or delete game objects.
Today I will simply record how to do these two things in Unity.
Preparation
We create two buttons for triggering event. One button is used to generate objects and the other one is used to delete game objects.
Prepare the objects to be generated and placed them in the Resources folder (you can create by yourself and the name cannot be wrong, because it is a dedicated folder in Unity).
At the same time, leave the targetParents
object in the scene, and wait for the following generated objects to become its children objects.
Generate a game object
Attach the generateEvent.cs script on Generate button.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class generateEvent : Button
{
// Button is Pressed
public override void OnPointerDown(PointerEventData eventData)
{
base.OnPointerDown(eventData);
}
// Button is released
public override void OnPointerUp(PointerEventData eventData)
{
base.OnPointerUp(eventData);
// Target
Object targetObject = Resources.Load("targetObject");
// Parent
GameObject parentObject = GameObject.Find("targetParents");
// Create
Instantiate(
targetObject,
parentObject.transform.position,
parentObject.transform.rotation,
parentObject.transform
);
}
}
Use Instantiate()
to generate objects, the parameters that need to be put in:
Instantiate(
The object you want to generate,
The object position,
The object rotation,
The object's parent object
)
Delete a game object
Attach deleteEvent.cs script on Delete button.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class deleteEvent : Button
{
// Button is Pressed
public override void OnPointerDown(PointerEventData eventData)
{
base.OnPointerDown(eventData);
}
// Button is released
public override void OnPointerUp(PointerEventData eventData)
{
base.OnPointerUp(eventData);
// Target
GameObject targetObject = GameObject.Find("targetParents").transform.GetChild(0).gameObject;
// Delete
Destroy(targetObject);
}
}
In the code, we find the first children object to delete it.
Destroy(DELETE_GAMEOBJECT);
Demo
References
- https://docs.unity3d.com/ScriptReference/Resources.Load.html
- https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.Button.html
- https://docs.unity3d.com/ScriptReference/Object.Destroy.html