environment:
- UnityHub3.3.0-c8
- Unity2021.3.20f1c1 LTS
- Visual Studio 2022
What is a GameObject
In Unity
, GameObject
is the most basic entity in the game. It can be seen as a container for all other objects in the game scene. GameObject
Can contain many different components, such as Transform、Renderer、Collider``等。通过添加这些组件,GameObject
can have different properties and functions, such as moving, rotating, displaying and interacting with other objects.
In Unity
, by creating, instantiating and managing GameObject
objects, a complete game scene can be constructed.
create
First create a 2D project by yourself
find a Hierarchy
column named
右键
It will automatically create a new GameObject
subject named . To view it, you need to select MoveTool
and click on the subject.
Choosing an Icon
We can perform and select operations Inspector
on it in the bar . Note that for empty objects, the previously selected content will be automatically displayed for the project that has just been started .rename
select icon
select icon
But Hierarchy
once the empty object is clicked and moved, this will not be displayed select icon
, and replaced with other objects, such as cube
the like, can be select icon
displayed. I don’t know if this is a problem with the latest version.
Alternatively, we can Game
view it in the
Of course, icon
we can also choose our own set of pictures in
GameObject Components
点击空对象
->看右侧Inspector栏
->Add Component
->Sprite Renderer
You can Sprite
click on our own sprites. The content that makes us excited or happy to hear and see all starts with a set of pictures.
If you want to add the picture we want, you only need to put the picture Project
you Assets
want in , and pull the picture into Sprite
the position of the picture below, and it defaults toBackground
GameObject Code
Project\Assets
Create a C# Script
script in the right click ->rename自己想要的名字
After that, throw the C# script you created into Hierarchy
the object you are creating, and you can perform debugging operations. The initial code content is as follows:
important point:
- The name of the class must be consistent with the name of your script. If you don’t start , the content in VS
rename
will not change after the creation is completedrename
, and you can’t enter it at this time.addComponent
GameObject
Dynamically Create GameObject
If you want to be able to create by code GameObject
, you can write like this:
void Start(){
new GameObject("MyNewGameObject");
}
Afterwards, run Add Component
any object of this script in , and a new column named " will be added , and it will disappear after running.unity
Hierarchy
MyNewGameObject
GameObject
If you want this new addition GameObject
to have addComponent
other content, for example Sprite Renderer
, the implementation method is as follows:
void Start(){
GameObject myGo = new GameObject("MyNewGameObject");
myGo.AddComponent<SpriteRenderer>();
}
or write like this
GameObject myGo = new GameObject("MyNewGameObject",typeof(SpriteRenderer));