-3

how to randomize ballValue from random range 1 to 100 so that each ball comes with different value random value for object

using UnityEngine;
using System.Collections;

public class HT_Score : MonoBehaviour {

    public GUIText scoreText;
    public int ballValue;
    private int score;

    void Start () {
        score = 0;
        UpdateScore ();
    }

    void OnTriggerEnter2D (Collider2D other) {
        score += ballValue;
        UpdateScore ();
    }

    void OnCollisionEnter2D (Collision2D collision) {
        if (collision.gameObject.tag == "Bomb") {
            score -= ballValue * 2;
            UpdateScore ();
        }
    }

    void UpdateScore () {
        scoreText.text = "SCORE:\n" + score;
    }
}

2 Answers2

0

your function shoule be look like

void GetRandomBallValue()
{
 ballValue=new Random().Next(1,100);
}
     void OnCollisionEnter2D (Collision2D collision) {
        if (collision.gameObject.tag == "Bomb") {
            GetRandomBallValue();
            score =ballValue * 2;
            UpdateScore ();
        }
    }
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70
0

You should not call new Random() everytime.

"Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance." See here: Random number generator only generating one random number

You also have to consider, that next() returns a random number from 1 to 100 (excluding 100). If you want 100 to be included, you need to call next(1, 101).

I would recommend to implement it the following way:

Random rnd = new Random();
void GetRandomBallValue()
{
    ballValue=rnd.Next(1,101); //excluding 101 - if you do not need 100, call Next(1,100);
}

void OnCollisionEnter2D (Collision2D collision) {
    if (collision.gameObject.tag == "Bomb") {
        GetRandomBallValue();
        score =ballValue * 2;
        UpdateScore ();
     }
}
Community
  • 1
  • 1
Skully
  • 347
  • 2
  • 4
  • 19