- Home /
transform.name value to a variable
might be a little funny, but how do I store the string value from a gameObject.name into a string-type var?
ex:
string _name = transform.name // throws an error, because I cannot establish a link to tweak the name variable, and I don't want to - I only need the value xD
A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.transform'
Sorry if this is too simple :D
Here is the code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NodeSpark : MonoBehaviour {
string string_name = gameObject.name; //throws the previously described exception
}//end of class
not understand what do you want to do :(
//C#
string string_name = gameObject.name;
//JS
var string_name : String = gmaeObject.name
that's the trick) with your example, you are establishing a link to the "name variable", you aren't copying it's variable.
Later on, if u change string_name's variable, it implies that you change the gameObject.name's value.
However, I only want to say that string_name becomes equal to the name's value
I've also updated the code, thank you for helping!
People don't even read the question. Yes, it is bad to assign a variable in the body of a class. But the question is not, what is wrong with this script? It is how do I get a copy of a string as opposed to a reference?
You always get a copy of the string. Strings are by value, not reference. The correct answer is to declare the variable outside functions, and assign the value inside Start or Awake. And yes, that's what the question is asking....
$$anonymous$$SDN on string says it's a reference type.
Answer by potatoking · Dec 30, 2013 at 09:34 PM
You can only do that inside of a function, so you could do that in the Start or Awake functions.
not only that))
It can also be done OnEnable using Editor
Answer by Eric5h5 · Dec 30, 2013 at 09:00 PM
Don't try to run code outside functions. Only declare variables outside functions; use Start or Awake to run initialization code.
// Declare variable only; run code that assigns a value in a function
string string_name;
Accept Eric5h5's answer.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NodeSpark : $$anonymous$$onoBehaviour
{
string string_name;
Awake()
{
string_name = gameObject.name;
}
}
@"Whoever downvoted this answer": Do you "think" or "feel" the answer is wrong or do you know it is wrong? Because it isn't.
If you see misinformation, vote it down. Insert comments indicating what, specifically, is wrong
We're still waiting for a clarifying comment :)
Well, I think potatoking's answer should be accepted since he was apparently first, but stuck in the moderation queue...if I'd checked the queue first I wouldn't have posted my answer since it's basically just what he posted.