- Home /
Adding a global custom component to GameObjects
I'm current trying to understand some of the logic behind unity engine and just can't wrap my head around this. Unfortunately looking at declarations and assemblies doesn't help at all.
Every GameObject in unity can have a transform, collider, rigidbody, renderer, etc as these properties are defined in class "Component", that derives from "Object".
My question is, how can I create a custom component (ie "MyGlobalComponent" with public field "delta") that every GameObject will have and can be accessed via code, for example:
public class MyClass : MonoBehaviour
{
public GameObject go; //set in editor
public int myInt = 0;
void Update ()
{
myInt = go.MyGlobalComponent.delta;
}
}
Thank you.
Answer by OrbitGames · Sep 04, 2014 at 01:13 PM
You need to create a reference to the "MyGlobalComponent".
This can be done via getComponent.
You can also do it without if your variable was static, that means the same for every gameobject.
In your case it would be (untested):
myint = transform.GetComponent<MyGlobalComponent>().delta;
if you want it from another you GO you should use
myint = go.transform.GetComponent<MyGlobalComponent>().delta;
hope this helps
Does "$$anonymous$$yGlobalComponent" must inherit from "Component" or any other class? And must I use AddComponent in the script that is attached to the "go" GameObject?
As expected, I need to add "$$anonymous$$yGlobalComponent" to each GameObject manually via editor or code. What I'm trying to achieve a is a custom component that each GameObject has automatically (like transform).
Although thanks, reading into get/set Component, I understand it usefulness much better now.
Your answer
![](https://koobas.hobune.stream/wayback/20220613162258im_/https://answers.unity.com/themes/thub/images/avi.jpg)