using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class GenerateAutomaticGuid : Editor
{
[MenuItem("GameObject/Generate Guid", false, 11)]
private static void GenerateGuid()
{
foreach (GameObject o in Selection.objects)
{
o.AddComponent<GenerateGuid>();
o.GetComponent<GenerateGuid>().GenerateGuidNum();
o.tag = "My Unique ID";
}
}
}
For example I’m selecting two gameobjects in the hierarchy right click and GenerateGuid I use a break point and it’s making a loop on each object in the list Selection.objects twice so each object in the list have the script GenerateGuid twice. And I want it to add the script to each object once only.
This is the GenerateGuid script :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateGuid : MonoBehaviour, IStateQuery
{
public string uniqueGuidID;
public SaveLoad saveLoad;
public GameObject naviParent;
private Guid guidID;
private bool isNaviChildOfKid = false;
public void GenerateGuidNum()
{
guidID = Guid.NewGuid();
uniqueGuidID = guidID.ToString();
}
private State m_state = new State();
public Guid UniqueId => Guid.Parse("E0B03C9C-9680-4E02-B06B-E227831CB33F");
private class State
{
public bool naviInHand;
}
public string GetState()
{
return JsonUtility.ToJson(m_state);
}
public void SetState(string jsonString)
{
m_state = JsonUtility.FromJson<State>(jsonString);
if (m_state.naviInHand == true)
{
transform.GetComponent<InteractableItem>().distance = 0;
transform.parent = GameObject.Find("Navi Parent").transform;//rig_f_middle;
transform.localPosition = GameObject.Find("Navi Parent").transform.localPosition;
transform.localRotation = Quaternion.identity;
transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);
}
}
private void Update()
{
if(transform.IsChildOf(naviParent.transform) == false && isNaviChildOfKid == false)
{
m_state.naviInHand = true;
saveLoad.Save();
isNaviChildOfKid = true;
}
}
}
A screenshot of all the places I’m calling the GenerateGuid :
I added a screenshot to my question of where I’m calling the GenerateGuid script or using. In two places I’m doing GetComponent to get this script and use it. In other two places are in the GenerateAutomaticGuid editor script. And I’m not calling anywhere to GenerateAutomaticGuid just using it with right click mouse when selecting objects.
And I used a breakpoint and if for example I selected two items in the hierarchy and did right click with the mouse and selected tp GenerateGuid it will loop 4 times in the foreach loop even if there are only two items.