Invincible gameObjects!?

Hi guys,

I’m working on a script that will allow an NPC to wander in random directions if he isn’t attacking or being attacked. I am doing this by using the following script. I want it to do the following:

create randomly placed gameobject, move toward randomly placed gameobject, if someTimer runs out, destroy the gameobject and create a new one.

My problem is the gameobjects dont destroy, some of them are called wanderTarget, like i have them set via code, and some are called wanderTarget(clone), not sure why. When they do “destroy” they leave empty shells with just a transform set to all 0’s.

I have a feeling its just making the reference to it null instead of actually destroying the gameobject… not entirely sure, thats what I need help with.

Here is my code:

	public void Wander(){
		_wanderWaitTimer = _wanderWaitTimer + Time.deltaTime;
		moveSpeed = GameSettings.LEISURE_SPEED;	
		if(_wanderWaitTimer > _wanderWait){
			GameObject wanderTarget = new GameObject();	
			wanderTarget.name = "wanderTarget";
			int x = Random.Range(MIN_WANDER_DIST,MAX_WANDER_DIST);
			int z = Random.Range(MIN_WANDER_DIST,MAX_WANDER_DIST);
			wanderTarget = Instantiate(
				wanderTarget,
				new Vector3((x + transform.position.x), transform.position.y, (z + transform.position.z)),
				Quaternion.identity) as GameObject;
			target = wanderTarget.transform;
			
			//must be able to be interrupted by seeing enemy
			
			if(Vector3.Distance (transform.position, target.position) < 1)
				Destroy(target.gameObject);
			
			_wanderWaitTimer = 0;
			_wanderWait = Random.Range(MIN_WANDER_WAIT, MAX_WANDER_WAIT);
		}
		
		if(target != null){
			PursueTarget();
		}
	}

Thanks all!

You are first creating a new game object in line 5. Then you clone the just newly created game object in line 9 (via Instantiate).

I assume you just want to position your newly created game object instead of cloning it. use wanderTarget.transform.position = new Vector3(...) instead of the Instantiate and you should be fine.


On some other note… Why do you create a game object to follow anyway? Why not just follow the target vector that you already calculate and skip all the game object creation/destruction?