Double collision with Character Controller? (418079)

Hi folks, i’m relatively new to programming and even more so with Unity.

What i’m trying to do is create Pac-man for a University Coursework. I have quite a lot of it working, however a new problem has arisen and I don’t know why.

Pac-man used to have a rigidbody attached to handle the collisions, however due to the forces applied (I think?) he kept bouncing off the maze walls. On further research I found the Character Controllers do not take forces into account. All was working well until I realised that more often than not double the score was given for each pellet consumed (sometimes the correct score was given). This only happened after I changed to Character Controller.

I’ve checked the log and it is incrementing by 100 but incrementing twice per collision. Any help is greatly appreciated.

Here’s my Consume code:

private var score : int = 0;
private var stringScore : String;
private var scoreObject : GameObject;

scoreObject = gameObject.Find("Score");

function OnControllerColliderHit(hit : ControllerColliderHit)
{
	var collide = hit.gameObject;
	if(collide.tag == "Pellet")
	{
		Destroy(collide.gameObject);
		score += 100;
		
		Debug.Log(score);
	}
	stringScore = score.ToString();
	scoreObject.GetComponent(TextMesh).text = stringScore;
}

Maybe the game detect two times in a row a collision because Unity did not have enough times to destroy it before going to the next frame.

By the way, the var collide already refers to the gameObject, as you wrote it, so you can simply write Destroy (collide).

Test 1 : Put yield before Destroy (collide).

Test 2 : Remove the previous yield, replace Destroy by DestroyImmediate.

Sorry I don’t know what you mean put yield before Destroy? Could you give an example please?

I tried DestroyImmediate and it unfortunately crashes Unity…

Ok I looked up yield and tried it, no luck there either…

Thanks for the help though, at least i’ve learned about the yield statement

You could add a variable to your script to remember the last pellet that you collided with. If the same pellet object is encountered again, just ignore it:-

var prevPellet: GameObject;

function OnControllerColliderHit(hit : ControllerColliderHit) 
{ 
   var collide = hit.gameObject; 
   if(collide.tag == "Pellet"  collide != prevPellet) 
   { 
      prevPellet = collide;
      Destroy(collide.gameObject); 
      score += 100;
      ...