Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How do I create a variable?

Discussion in 'Scripting' started by InfiSnyp, May 5, 2016.

  1. InfiSnyp

    InfiSnyp

    Joined:
    Mar 25, 2016
    Posts:
    21
    In my script I access a public float from another script by using

    Code (CSharp):
    1. private Counter playerScript;
    2.  
    3. playerScript = GameObject.Find("Text").GetComponent<Counter>();
    4. //print(playerScript.myTimer);
    I can print the

    Code (CSharp):
    1. playerScript.myTimer
    But I can't do something like

    Code (CSharp):
    1. if playerScript.myTimer >= 0{
    2.     randomSpawnRate = Random.Range(0.9f, 0.99f);
    3. }
    So maybe a variable would solve this?

    Thanks!
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,886
    You have to put it in parenthesis/brackets:

    Code (CSharp):
    1. if (playerScript.myTimer >= 0)
    2. {
    3.     randomSpawnRate = Random.Range(0.9f, 0.99f);
    4. }
     
    Kiwasi likes this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    For the record myTimer probably is a variable.
     
  4. InfiSnyp

    InfiSnyp

    Joined:
    Mar 25, 2016
    Posts:
    21
    Yea "myTimer" is a variable.

    Code (CSharp):
    1. public float myTimer = 0;
    But I want to do the same for "playerScript.myTimer" so I don't always have to put that in if statments.

    So find like

    Code (CSharp):
    1. float ppp = (playerScript.myTimer);
    Although I'm sure that's not the way to do it.
     
  5. McMayhem

    McMayhem

    Joined:
    Aug 24, 2011
    Posts:
    443
    What is it you don't want to put in if statements? If playerScript.myTimer is a float, you can use that as @Stardog showed in the reply above. As long as playerScript is actually set to something, it should always work.

    If you're looking to shorten playerScript.myTimer, then you can assign it to a float located in the script you're using it in.

    Code (CSharp):
    1.  
    2. float pTime = playerScript.myTimer;
    3.  
    4. if(pTime >= 0)
    5. {
    6. //Do whatever you want here
    7. }
    Is that what you mean?
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Just be aware that a float is a value type. Doing it this way means pTimer will not update when myTimer changes. Not a problem if you do it immediately before the if. But it won't work in say Start when the if is in Update.