I want to assign a unique id to gameobject every time I attach a certain Script to it

I have custom dll file in which there is script that I attach to unity game object in editor ,I want to also add a unique ID along with this Script to that gameobject, For example – when I select the gameobject and attach the script to it ,I want to attach unique Id at same time . in short I need a event or callback function that will be executed every time I attach my custom script to any gameobject.

Hi,anujmar27
First let get something clear. I assume you want to do it both inedit and play mode so I added [Execute Always]. If you want it to be only in Edit Mode you can replace it with [ExecuteInEditMode]. Third you need to do some presets and two scripts.

First script is the i storer you need assign it only to one object (it dosen’t matter which one just make sure assigned game object is active).

Second script is the ObjectNamer. Assign it to every object that you want to change name when your custom script is assigned.

Inspectors should look like this:

[201125-ekran-alıntısı.jpg|201125]

[201126-ekran-alıntısı-2.jpg|201126]

these are the scripts

using UnityEngine;

[ExecuteAlways]
public class ObjectNamer : MonoBehaviour
{
    public bool IsRenamed;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {  
        //Replace NewBehaviourScript with the name of your custom script.
        if (gameObject.GetComponent<NewBehaviourScript>() != null)
        {
            if (gameObject.GetComponent<ObjectNamer>().IsRenamed == false)
            {
    gameObject.name = "Object with script attached " + GameObject.FindObjectOfType<iStorer>().i;
                IsRenamed = true;
                GameObject.FindObjectOfType<iStorer>().i++;
            }

        }

    
    }
}

using UnityEngine;

public class iStorer : MonoBehaviour
{
    public int i;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Hope this helps. Also feel free to ask if you are confused about something. I will try ro answer as soon as I see it.