Findgameobjectwithtag Unity
Example of how to access another GameObject's component
GetComponentExample.cs
GameObject.FindGameObjectWithTag('タグの名前') これはオブジェクトの名前ではなく、オブジェクトにつけられたタグの名前からオブジェクトを見つけるものです。 注意点としてGameObject.Findと同じくアクティブなものしか取得できないことです。. Unity3d C# most common static methods available in the GameObject class are shown in this video. We go through 7 different examples and examine through the U. FindGameObjectWithTag has a complexity O (n) in the worst case scenario. You will not have performance issue if you have small amount of objects in your scene and small amount of objects searching for objects with tags. Another approach is by serializing these.
usingUnityEngine; |
publicclassGetComponentExample : MonoBehaviour |
{ |
// First we need a reference to the other gameobject |
// You can make a public field and assign a prefab in the inspector |
publicGameObjectsomePrefab; |
// Or you can search for a gameobject and assign it to a variable |
privateGameObjectgameObjectFoundBySearch; |
voidStart() |
{ |
// You can find a gameobject by name |
gameObjectFoundBySearch=GameObject.Find('Sphere'); |
// Or you can find it using the gameobjects tag |
gameObjectFoundBySearch=GameObject.FindGameObjectWithTag('Tag'); |
// Tip: Don't use GameObject.Find or GameObject.FindGameObjectWithTag in Update since |
// it's a heavy operation that scales with the amount of gameobects you have in the scene. |
// Call it in start and save the reference in a member variable. |
} |
voidUpdate() |
{ |
// Now to acces a component on the gameobject, |
// simply use the generic GetComponent method |
TypeOfComponentGoesHerecomponent=gameObjectFoundBySearch.GetComponent<TypeOfComponentGoesHere>(); |
// Tip: You can also use GetComponent in Start() and save a reference to the component |
// in a member variable, so GetComponent isn't called every frame. This is called caching |
// the component and is a very good practice! |
// You can now use the public methods etc. on the component of the gameobject |
component.DoStuff(); |
} |
} |

Findgameobjectwithtag 複数
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment
