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

[Javascript] Reference to an object/property.

Discussion in 'Scripting' started by KinxilTheHarpist, Feb 24, 2015.

  1. KinxilTheHarpist

    KinxilTheHarpist

    Joined:
    Jun 30, 2014
    Posts:
    11
    Hello ladies and gentlemen,

    I would like to know if it was possible on a script (or even on all of them at once ?) to create some kind of text reference to mean an object or property ?

    For example to make it clear, I often have to type ridigbody2D.velocity.x or rigidbody2D.velocity.y in my current project, and I would love to be able to type xSpeed and ySpeed to read/modify these value.

    Thanks in advance.
     
  2. jallen720

    jallen720

    Joined:
    Feb 22, 2015
    Posts:
    66
    You can try getters/setters:

    Code (JavaScript):
    1. function GetSpeedX() : float {
    2.     return rigidbody2D.velocity.x;
    3. }
    4.  
    5. function SetSpeedX(x : float) {
    6.     rigidbody2D.velocity.x = x;
    7. }
    8.  
    9. function GetSpeedY() : float {
    10.     return rigidbody2D.velocity.y;
    11. }
    12.  
    13. function SetSpeedY(y : float) {
    14.     rigidbody2D.velocity.y = y;
    15. }
    Unfortunately UnityScript doesn't allow text macros.
     
    Last edited: Feb 24, 2015
  3. Xoduz

    Xoduz

    Joined:
    Apr 6, 2013
    Posts:
    135
    Alternative way of doing it:
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. private var _rigidbody2D : Rigidbody2D;
    4.  
    5. function Start () {
    6.     _rigidbody2D = GetComponent( Rigidbody2D );
    7.     xSpeed = 2;
    8.     ySpeed = 2;
    9. }
    10.  
    11. function Update () {
    12.     Debug.Log( ySpeed );
    13.     Debug.Log( xSpeed );
    14. }
    15.  
    16. function get xSpeed() : float {    return _rigidbody2D.velocity.x; }
    17. function set xSpeed(value : float) { _rigidbody2D.velocity.x = value; }
    18. function get ySpeed() : float { return _rigidbody2D.velocity.y; }
    19. function set ySpeed(value : float) { _rigidbody2D.velocity.y = value; }
     
  4. jallen720

    jallen720

    Joined:
    Feb 22, 2015
    Posts:
    66
    Better way of doing it!