Version: 2021.1

Object.GetInstanceID

切换到手册
public int GetInstanceID ();

返回

int Returns the instance ID of the object. When used to call the origin object, this method returns a positive value. When used to call the instance object, this method returns a negative value.

描述

Gets the instance ID of the object.

The instance ID of an object is always unique.
The ID changes between player runtime and Editor sessions. As such, the ID is not reliable for performing actions between the Editor and runtime sessions, for example, loading an object state from a save file.

using UnityEngine;

public class ExampleScript : MonoBehaviour { // Create 10 game objects, which will have random Instance IDs void Awake() { for (int i = 0; i < 10; i++) { GameObject go = new GameObject("abc" + i.ToString("D3")); } }

// Find all the game objects and display their Instance IDs void Start() { Object[] allObjects = Object.FindObjectsOfType<GameObject>();

foreach (GameObject go in allObjects) { Debug.Log(go + " is an active object " + go.GetInstanceID()); } } }