In my scene there is a 3D Text object with a script assigned to it.
The script is a simple MonoBehaviour script and looks like this:
using UnityEngine;
using System.Collections;
public class DisplayHighscore : MonoBehaviour
{
// Use this for initialization
void Start()
{
GetComponent(TextMesh).text = "hi";
}
}
But I get these three error messages and I have no idea why.
error CS0119: Expression denotes a type', where a variable’, value' or method group’ was expected
error CS1502: The best overloaded method match for `UnityEngine.Component.GetComponent(System.Type)’ has some invalid arguments
error CS1503: Argument #1' cannot convert object’ expression to type `System.Type’
I hope one you knows what’s going wrong here…
btw:
when I do it like this I don’t get an error, but nothing happens:
TextMesh text = (TextMesh)GetComponent(typeof(TextMesh));
text.text = "hi";
I can confirm that your code works. Tested on Unity 4.2
// Use this for initialization
void Start ()
{
TextMesh text = (TextMesh)GetComponent(typeof(TextMesh));
text.text = "hi";
}
As for the Question of why the previous code doesn’t work, its simple. This line is wrong:
TextMesh text = GetComponent(TextMesh);
GetComponent expects a “type” as its parameters, whereas you are passing it an object. The correct way to do it would be this:
GetComponent(typeof(TextMesh));
Also, the “return” value of this function is a generic object. In order to use it as a TextMesh, you must “cast” it into a TextMesh like this: (TextMesh)GetComponent…
So the final code looks like this:
TextMesh text = (TextMesh)GetComponent(typeof(TextMesh));
Should do it like this if the script is in the actual 3D Text object:
using UnityEngine;
using System.Collections;
public class changeMe : MonoBehaviour {
TextMesh my3dText;
// Use this for initialization
void Start () {
my3dText = transform.GetComponent<TextMesh>();
}
// Update is called once per frame
void Update () {
my3dText.text = "Hi there dude";
}
}