Miss Pixel Miss Pixel - 9 months ago 51
C# Question

How can I disable the game to count for more than one for each object?

I am using C# with Unity and trying to practice this example
I want the game to count when the ball collide each cube for once only, but it seems the ball count for the same cube whenever it find a collide between them, so how can I make an object in an object in a prefab disabled to be changed but still visible ?

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour {

public float speed;
public Text countText;

private Rigidbody rb;
private int count;

void Start ()
{

rb = GetComponent<Rigidbody>();
count = 0;
SetCountText ();
}

void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

rb.AddForce (movement * speed);
}

void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ( "Pick Up"))
{
// How it can know which one of the object in the prefab that tagged to "Pick Up" is selected ? and how can make it disabled to be effected by the ball in the second time after the collide ?
count = count + 1;
SetCountText ();
}
}

void SetCountText ()
{
countText.text = "Count: " + count.ToString ();
}
}

Answer Source

If you destroy the "other" collider, then it can't collide again. Or you can disable it, if you prefer, but it would mean the same thing.

void OnTriggerEnter(Collider other) 
    {
        if (other.gameObject.CompareTag ( "Pick Up"))
        {
            // How it can know which one of the object in the prefab that tagged to "Pick Up" is selected ? and how can make it disabled to be effected by the ball in the second time after the collide ?
            count = count + 1;
            SetCountText ();
            Destroy(other); // Add this...
        }
    }