I’m really new to Unity but having a lot of fun with it so far and have been following one of the Packt books “Getting Started with Unity”. Pretty short but enough to get the ideas flowing
The code in the book is in Javascript and for the most part I have been fine translating into C# (as I have more experience with this from windows app creation and asp sites.) I am however stuck with one concept:
displayMessageToUser is a seperate script and I have made the displayText method public but I keep getting an number of errors. I’ve read a few suggestions that indicate the following:
error CS1061: Type UnityEngine.Component' does not contain a definition for displayText’ and no extension method displayText' of type UnityEngine.Component’ could be found (are you missing a using directive or an assembly reference?)
Any suggestions would be greatly appreciated. If there is any more information you need, please let me know. Cheers
I suggest you look up some of the basics of C#. The problem you’re having is in the type system. Javascript/Unityscript are not strongly typed languages. It infers the type of expressions in the compiler, so you don’t have to worry about it. This has some major downsides, but I won’t go into them here. The problem is that C# IS a strongly typed language. It requires that the type of expressions be clear and accurate at all times, and that types cannot change without being explicitly told to. The issue is that the call to GetComponent returns an object of type Component. In Unityscript, it automatically converts this to the type you need. In C#, it doesn’t make such a conversion, and since the type Component doesn’t have any reference to a method called displayText, it doesn’t know what to do, and throws an error. You can fix this by casting the first expression to the correct type. Here is some information on C# type casting.
There is, however, another, more elegant solution, provided with Unity, and that is to use generics. Generics allow a single method to be applied to various types, allowing the code to be clearer, more secure, and not repeated multiple times. Generics use angle bracket notation, with a type inside, like this: GenericMethod(). This will call a specific version of the GenericMethod, for the type Type. Now keep in mind that this only works because Unity have defined a generic version of GetComponent - not all methods are generic. Here is some information on C# generics.
That done, here are some more helpful links that should point you in the right direction:
I assume displayMessageToUser is the name of your script class here. Normal convention would be to capitalise the first letter for classes as it makes for a bit easier reading.