- Home /
Why do I have to explicitly cast my MovieTexture?
Shouldn't unity automatically know that the maintexture is a movietexture and allow access to Play()? It just seems a little clunky, but I'm by no means an expert programmer.
Currently I have to use the following code and cast the texture as a MovieTexture before I can play it:
MovieTexture movieTexture;
// Use this for initialization
void Start () {
movieTexture = renderer.material.mainTexture as MovieTexture;
movieTexture.Play ();
}
Thank you for any explanations!
Answer by Bunny83 · Dec 13, 2013 at 04:03 AM
No ;)
Strong typed languages always require casting in such situations. That's because a material can reference any type of Texture. It could be a Texture2D or a MovieTexture. The material just needs a "Texture". Since Texture2D and MovieTexture are derived classes from Texture they can be assigned to mainTexture, however the Material just knows it has a material. Casting actually performs a type check at runtime.
The normal cast throws an exception if the cast fails (for example when you have a Texture2D but you try to cast it to a MovieTexture).
movieTexture = (MovieTexture)renderer.material.mainTexture;
The as-cast doesn't throw an exception but if the cast fails it simply returns null. In some situation that's quite useful. However in most cases this is hard to debug since the runtime doesn't tell you what's actually wrong. In your code, if the cast fails, you would get a null-reference-exception in line 6 but the actual (logical) mistake was in line 5.
That's why you usually use the normal cast.
Your answer
Follow this Question
Related Questions
C# - Resources.Load Sprite trouble 2 Answers
Changing texture when movie is paused 0 Answers
How to cast/convert a ControllerColliderHit into a Prefab 2 Answers
play movie texture smoothly in unity 0 Answers
Is There A Way To Cast On 1 Returning Value 2 Times? 5 Answers