- Home /
Question by
ForbiddenSoul · Jan 29, 2016 at 06:54 AM ·
c#gameobject.find
Procedural Named Object Is Named, Procedural Find Object By Name Doesn't Work?
So I have some code that looks like this:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class TerrainExtensions {
/// <summary>
/// Adds Collider for a TreeInstance to the TreeInstanceColliders GameObject.
/// Intended to be used when "Enable Tree Colliders" is disable in the Terrain Collider Component
/// </summary>
/// <param name="terrain"></param>
/// <param name="treeInstance"></param>
public static void AddTreeInstanceCollider(this Terrain terrain, TreeInstance treeInstance)
{
// If there is not a TreeIntanceColliders GameObject, create one so we can use it as the parent for the new collider(s)
if (GameObject.Find("TreeInstanceColliders") == null)
{
GameObject treeInstanceColliders = new GameObject();
treeInstanceColliders.name = "TreeInstanceColliders";
}
// Create TreeIntanceCollider GameObject
GameObject treeInstanceCollider = new GameObject();
treeInstanceCollider.name = "TreeInstanceCollider " + Array.IndexOf(terrain.terrainData.treeInstances, treeInstance);
treeInstanceCollider.transform.parent = GameObject.Find("TreeInstanceColliders").transform;
}
That part works fine. If I have 10 TreeInstances Unity names them "GameObject 0" through "GameObject 9". Good.
Then I call some code that looks like this:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class TerrainExtensions {
/// <summary>
/// Removes a TreeInstanceCollider
/// </summary>
/// <param name="terrain"></param>
/// <param name="treeInstance"></param>
public static void RemoveTreeInstanceCollider(this Terrain terrain, TreeInstance treeInstance)
{
GameObject treeInstanceCollider = GameObject.Find("TreeInstanceCollider " + Array.IndexOf(terrain.terrainData.treeInstances, treeInstance));
if (treeInstanceCollider != null)
{
GameObject.Destroy(treeInstanceCollider);
}
else
{
Debug.LogError("Failed to RemoveTreeInstanceCollider " + Array.IndexOf(terrain.terrainData.treeInstances, treeInstance) + ". Deos it exist?");
}
}
}
The error about not being able to find the game object is always thrown, as for some reason the array index is always returned as -1 regardless of what I know it to be.
How do I get GameObject.Find() to return the GameObject I want? I'm sure it's probably something silly again... Thanks!
Comment
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer
GameObject.Find Unity 5.3+ 1 Answer