Search Unity

Scripting Changes to Unity 5

Discussion in 'Scripting' started by bscarl88, Jul 8, 2015.

  1. bscarl88

    bscarl88

    Joined:
    May 11, 2012
    Posts:
    39
    I'm doing the project stealth tutorial after doing the survival shooter, and it seems that there was a major change as to how to access the components and object properties the script is attached to.

    Here's what they call for in code:

    Code (CSharp):
    1. public class LaserBlinking : MonoBehaviour
    2. {
    3.     public float onTime;            // Amount of time in seconds the laser is on for.
    4.     public float offTime;           // Amount of time in seconds the laser is off for.
    5.    
    6.    
    7.     private float timer;            // Timer to time the laser blinking.
    8.    
    9.    
    10.     void Update ()
    11.     {
    12.         // Increment the timer by the amount of time since the last frame.
    13.         timer += Time.deltaTime;
    14.        
    15.         // If the beam is on and the onTime has been reached...
    16.         if(renderer.enabled && timer >= onTime)  //*****
    17.             // Switch the beam.
    18.             SwitchBeam();
    19.      }
    20. //I left the rest out)
    21.  
    The line where I added the "//*****" my "enabled' is in RED highlighting an error. Do I have to define the object that the script is attached to as a private variable first in order to access the renderer? I've seen stuff like this a lot with the previous tutorials, but I haven't seen anyone explain what was changed so that their script works fine as is, but extra steps are needed?
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Replace renderer with GetComponent<Renderer>()
     
  3. bscarl88

    bscarl88

    Joined:
    May 11, 2012
    Posts:
    39
    thanks! that worked, but I'm really interested in what was changed between unity 4.x - 5 to make the script logic not work the same so I understand better.
     
  4. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    This is the case for all component shortcuts (renderer, rigidbody, collider, etc)
     
    Kiwasi likes this.
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
  6. bscarl88

    bscarl88

    Joined:
    May 11, 2012
    Posts:
    39