Search Unity

Random Number Generation: new coder question.

Discussion in 'Scripting' started by Shobosa, Aug 9, 2016.

  1. Shobosa

    Shobosa

    Joined:
    Jul 8, 2015
    Posts:
    18
    I am new (should be obvious from the code below). I am trying to click on an image and have the generate or run a script that will produce 1 random range number. I want this number to then show up in a spot I have set up on the game. Right now it just prints to console. Can someone assist me please.

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

    public class number_gen : MonoBehaviour
    {
    //public int firstSpot;
    public string firstSpot;

    //private int firstSpot;
    int secondSpot;
    int thridSpot;
    int forthSpot;
    int fifthSpot;

    void Start ()
    {
    string firstSpot = Random.Range (0,90);
    //string ="firstSpot" + firstSpot.ToString();
    firstSpot.ToString();
    //print (firstSpot);
    }
    }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    If you are using unity's UI system, you'll need a text object in the scene. Then you just assign the string like so

    myTextObject.text = firstSpot;
     
  3. Shobosa

    Shobosa

    Joined:
    Jul 8, 2015
    Posts:
    18
    I can't tell you how much I wish I understood this like you all do. I have a UI text object in the game andI did this
    using UnityEngine;
    using UnityEngine.UI;
    using System.Collections;

    public class number_gen : MonoBehaviour
    {
    public Text firstSpot;
    public int myTextObject;

    void Start ()
    {
    myTextObject = Random.Range (0,90);
    myTextObject.text = firstSpot;

    }
    }

    I get this error ::::(17,30): error CS1061: Type `int' does not contain a definition for `text' and no extension method `text' of type `int' could be found (are you missing a using directive or an assembly reference?)

    so lost....
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    well, your text object is actually firstSpot now.
    If you want to use firstSpot as your text object, that's fine, but the naming would seem funny on your int. But, just to keep your naming convention.
    Code (CSharp):
    1. void Start ()
    2. {
    3. myTextObject = Random.Range (0,90);
    4. firstSpot.text = myTextObject.ToString();
    5.  
    6. }
    Make sure you drag something into the text variable slot in the inspector.

    I would suggest you look into beginner tutorials as well, or else this will be a struggle for you the entire way and will most likely result in your frustration and dropping of the project.