Can`t find a tagged object

I have two spheres: ones in the scene, anothers a prefab.
When I click on the first sphere, the second one instantiates.
Then I would like to measure the distance between my 2 spheres.
My first sphere is tagged ‘target’.

Object1 = GameObject.FindGameObjectsWithTag(“Cube”).transform;

Here is the code I`m using to find it.

Here is the mistake I get:
Assets/Ueban.cs(26,70): error CS1061: Type UnityEngine.GameObject[]' does not contain a definition for transform’ and no extension method transform' of type UnityEngine.GameObject’ could be found (are you missing a using directive or an assembly reference?)


Would you please suggest the easiest way to find the target for my newly instantiated object?
Thank you!

Your problem is you’re trying to call .transform on an array of GameObjects.

Object1 = GameObject.FindGameObjectsWithTag("Cube").transform;

change this to

Object1 = GameObject.FindWithTag("Cube").transform;

FindWithTag will return the first object it finds with this tag.

However, finding objects should be a last resort as it’s very slow when you have many objects in your scene. I’d recommend just storing your newly instantiated GameObject so you can use it later rather than having to find it.

GameObject myNewGameObject = Instantiate( prefab, position, rotation ) as GameObject;

When you instantiate the object, instantiate it as a GameObject like this

GameObject cloneSphere = Instantiate(Object, transform.position, transform.rotation) as GameObject;

then just find distance between these 2 objects in the same script that you instantiate so now you can use cloneSphere.transform.position rather than needing to find a tag, or you can reference than gameobject to another script, much easier