Reputation: 107
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.
Upvotes: 3
Views: 14622
Reputation: 17
You can add a script to the prefab from which an object is created using the Instantiate method. In this script, you declare public variable. Then you can change and get the value of this variable using the GetComponent method.
The code in script file added to the prefab (prefab name is thatPrefab
, script file name is IdDeclarer
) as a component:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IdDeclarer : MonoBehaviour
{
public int id;
}
Declaring an object's characteristics (ID in example):
GameObject newObject = Instantiate(thatPrefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
newObject.GetComponent<IdDeclarer>().id = 99;
Debug.Log(newObject.GetComponent<IdDeclarer>().id);
Output: 99
I hope I helped you
Upvotes: 1
Reputation: 1690
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.
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.
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.
After drag and drop
Now you can reach every subComponent of cube object. In red rectangle I reached it's Transform component and changed it's position.
I hope I understood your question correct.GL.
Upvotes: 3
Reputation: 53958
If GameObject
wasn't a sealed class then inheritance could have been the solution to your problem. In this ideal situation you could try the following.
public class ExtraGameObject : GameObject
{
// Logically you could make use of an enum for the
// color but I picked the string to write this example faster.
public string Color { get; set; }
}
A solution to your problem could be to declare your class like below:
public class ExtraGameObject
{
public string Color { get; set; }
public GameObject GameObject { get; set; }
}
I am aware of this that this is not exactly that you want, but that you want I don't think that it can be done due to the sealed nature of GameObject
.
Upvotes: 2
Reputation: 1566
Christos answer is correct. You cannot add a variable to the GameObject datatype because it was built into the language as a base. To add variables to premade data type, extend off of them. For more information on inheritance see
https://msdn.microsoft.com/library/ms173149(v=vs.100).aspx
Upvotes: 0