Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a c# script run at scene start in unity

Tags:

c#

unity3d

I am doing a school project. I need to check the destroyed objects in my scene as soon as the scene starts. problem is I don't know how to make it load or where to attach the c# script.

public static class DestroyedObject {

    static List<GameObject> objs = new List<GameObject>();
    public static void Add(GameObject obj) 
    {
        if(!objs.Contains(obj))
            objs.Add(obj); 
    } 
}
like image 892
Jr Rosales Avatar asked Jan 09 '17 13:01

Jr Rosales


People also ask

What is the material of AC?

11.4. Air conditioners are made of different types of metal. Frequently, plastic and other non-traditional materials are used to reduce weight and cost. Copper or aluminium tubing, critical ingredients in many air conditioner components, provide superior thermal properties and a positive influence on system efficiency.


2 Answers

If you want it to run when you start the scene you need to attach it to a GameObject. Create empty and attach it as a component.

The code that you want to run on start should be in the:

void Awake
{
    //Your code here
}

or

void Start
{
    //Your code here
}

functions.

Start is called as soon as the class is instantiated and Awake is called when the scene is started. Depends where you want it in the call stack, but in your case i think it will do essentially the same thing.

like image 189
creole-basterd Avatar answered Sep 28 '22 09:09

creole-basterd


I think what you're looking for is a way to "save" what objects have been deleted : you simply have to make your class inherit from MonoBehaviour and call DontDestroyOnLoad() so your object containing the script will exist between the scenes.

public static class DestroyedObject : MonoBehaviour
{
    public static DestroyedObject Instance;
    private static List<GameObject> objs = new List<GameObject>();

    private void Awake()
    {
        if (!Instance)
        {
            Instance = this;
        }
        else
        {
            DestroyImmediate(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }

    public static void Add(GameObject obj) 
    {
        if(!objs.Contains(obj))
            objs.Add(obj); 
    }

    public static List<GameObject> GetDestroyedObjects()
    {
        return objs;
    }
}

Then you simply access your script using DestroyedObject.Instance.Add() or DestroyedObject.Instance.GetDestroyedObjects() (some people don't like this kind of design pattern but it has proven to be very effective when using Unity).

Also as @Sergey asked, why creating objects (on scene loading) in order to delete them afterward : you could do the revers operation (only instantiate the needed ones).

Hope this helps,

like image 38
Kardux Avatar answered Sep 28 '22 10:09

Kardux