davidroman
davidroman

Reputation: 15

How to create a global object on C#

I´m making a simple CAD application on Unity 3D using C# to configure closets. Right now i have a few scripts and classes and I need to make the closet a global object accessible for every script of the project.

I tried setting the closet class as static but, since its modified every time I cant make it that way. Is the first time I work with C# and im kinda lost.

Upvotes: 0

Views: 2078

Answers (3)

davidroman
davidroman

Reputation: 15

My bad, dont know why but the first time I tried with static it came up with some errors but now it worked fine. I can access to this object from anywhere.

Upvotes: 0

P. Fouilloux
P. Fouilloux

Reputation: 21

Rather than a global, I would recommend creating a GameObject which you can then find in your scripts using GameObject.Find() method.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    private GameObject cabinet;
    void Start() {
        //find the cabinet object in your scene
        cabinet = GameObject.Find("Cabinet");
    }
}

Upvotes: 2

johnny 5
johnny 5

Reputation: 20987

I was facing the same issue a while back. The solution I came up with is simple Create a WorldGameObject in which all objects derive from this in the project hierarchy

Then if you want you can call this code in all classes or create a base class which gets the parent via the root

using UnityEngine;
using System.Collections;

//Add this class to your world game object and store your globals here
public class GlobalContext : MonoBehaviour{
}

public class BaseClass : MonoBehaviour {
    private GlobalContext world;
    void Start() {
        //find the cabinet object in your scene
        world= transform.root.GetComponent<GlobalContext>();
    }
}

Upvotes: 0

Related Questions