K
K
KeysCG2021-08-19 21:45:21
Unity
KeysCG, 2021-08-19 21:45:21

How to make an item collection limit?

Good day! Help me please.
I made a script that allows you to collect items and display their number on the screen, but I can not figure out how to make a limit on the collection of items. That is, for example, so that it would be impossible to collect more than 20 items (so that they simply do not rise more if there are already 20 of them)
Here is the code:
This is hung on the character:

public class rock_player : MonoBehaviour {
  static public int rock; 

  [SerializeField]
  public Text TextRock; 

  void Start(){
    rock = 0; 
  }
}

This is hung on the object that we raise:
public class RockTrig : MonoBehaviour {
  public int ValueRock; 

  void OnTriggerEnter(Collider col) { 
    rock_player.rock += ValueRock; 
    GameObject.FindGameObjectWithTag ("Player").GetComponent<rock_player> ().TextRock.text = rock_player.rock.ToString(); 
    Destroy (gameObject);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Polishchuk, 2021-08-19
@PNECtarine

I think it's better to track the trigger on the character, then we can count the number of items and set the condition under which the items will be collected. If the trigger is needed exclusively on the subject, then just set a condition (as I understand it, rock_player.rock)

T
twobomb, 2021-08-19
@twobomb

public class rock_player : MonoBehaviour {
  static public int rock; 
  public const int MAX_ROCKS = 20; 

  [SerializeField]
  public Text TextRock {get { return rock.ToString();}}

  void Start(){
    rock = 0; 
  }
}

public class RockTrig : MonoBehaviour {
  public int ValueRock; 

  void OnTriggerEnter(Collider col) { 
  if(rock_player.rock + ValueRock > rock_player.MAX_ROCKS) {
        ValueRock -= rock_player.MAX_ROCKS - rock_player.rock;
         rock_player.rock = rock_player.MAX_ROCKS; 
}else{
    rock_player.rock += ValueRock; 
    Destroy (gameObject);
}

  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question