- Home /
Best way to handle many versions of same GameObject?
Hey guys, beginner to Unity here working on a side-perspective drag racing game that I ported from Scirra Construct 2. In Construct I handled different vehicle types simply with a variable (carType) and changing the animation frame of one object (car) as needed. So if carType == 1 then the animation frame of the car object changes to 1 which appears as a car a, followed by more code to adjust vehicle specifications. How would I go about doing something similar in Unity? Or would I have to create a unique gameObject for each car I'd like to implement? Basically what I'm asking is, is it possible to change the sprite for a gameObject on the fly in runtime? If so, how? Thanks
Answer by kaplica · Oct 13, 2017 at 06:13 PM
Assuming that carGo is a gameobject with an image component that contains the sprite of the car then:
var carGo = GetComponent<Image>.sprite = newSprite;
The "right" way would be to create a general Car class, and then you would inherit from that class and make different types of cars. Read about OOP and composition.