Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3D/C# - add a variable to gameobject

How can I add a variable to a GameObject? GameObjects have a series of variables (name, transform, ...) that can be accessed and modified from any script. How could I add a variable such as for example "color" or "type" that could be accessed or modified from other scripts. Thanks.

like image 264
cubecube Avatar asked Dec 22 '25 13:12

cubecube


1 Answers

As every object in c# GameObject class inheritance Object class. If you right click on GameObject and select go to definition you will see that below. enter image description here

In order to reach one object's variables you need a reference(not considering static variables). So if you want to change variables of one GameObject from other you need a ref. enter image description here On Unity inspector you can assign values to public variables of a script. Below you can see Obj end of the arrow. Now assign cube(is a GameObject ) to Obj. enter image description here After drag and drop

enter image description here

Now you can reach every subComponent of cube object. In red rectangle I reached it's Transform component and changed it's position. enter image description here

I hope I understood your question correct.GL.

like image 66
Burak Karasoy Avatar answered Dec 24 '25 03:12

Burak Karasoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!