Search Unity

Combination of a script requires place of code in two different spaces than it should

Discussion in 'Scripting' started by Anon1234, Nov 28, 2014.

  1. Anon1234

    Anon1234

    Joined:
    Feb 17, 2014
    Posts:
    78
    Okay, well, title is pretty wanky. I have 6 elements.

    ### (sphere)
    @@@ (sphere)
    !!! (sphere)
    ### DESC (GUIText)
    @@@ DESC (GUIText)
    !!! DESC (GUIText)

    I wanted to do as if I was smart, I wanted to put just one script on all the spheres, so that it would initialize GUIText rather easily. Just one script that would add "DESC" on the end of name.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class GUI_boost_indexer : MonoBehaviour {
    5.     string TemporaryVariable = this.name + " DESC";
    6.     public GUIText TemporaryVariable;
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.    
    11.     }
    12.    
    13.     // Update is called once per frame
    14.     void Update () {
    15.     }
    16. }
    Placing code this way, it says that "this" doesn't exist in current context.
    Placing the two lines (obvious which), within start function. Gives errors in public GUIText, because it needs to be initialized before Start() is.

    How do I initialize GUIText if GUIText variable should be only this.name + " DESC"; with just one script? With just 1 or 2 lines? I think this is most efficient way for it.
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    transform.name instead of this.name.
     
  3. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,706
    You can't use "this" in the variable declaration part of your class, but you can use it inside a method:
    Code (csharp):
    1. public class GUI_boost_indexer : MonoBehaviour {
    2.    void Start () {
    3.      GetComponent<GUIText>().text = this.name + " DESC";
    4.   }
    5. }
    (BTW, transform.name and this.name are equivalent. They both return the name of the GameObject. If you want the name of the script type, use this.GetType().Name.)