Hi! I’ve learned programing not too long ago and was curious to see if it were possible to make an Image change on a prefab based on enum value.
I’m not sure if its necessary to say, but I have multiple values pulling from the same list i.e. each object can have multiple values from the same enum.
Thanks for the assistance!
It’s definitely possible, though how to do so depends what you mean specifically. Do the prefabs define their own Enum → Image table, or does a particular enum refer to a particular image on a global basis?
That said, I would try to avoid enums if possible. You could either use scriptable objects to define the type of image (it could reference the image itself), or just pass the image/sprite directly.
The enum would refer on a global bases I suppose. I plan on using the images in multiple prefabs.
Why would you advise away from enum? I’ve been learning c#/unity for about 3 weeks so any knowledge you can bestow would be a godsend.
They can make your code very rigid, and the enums themselves don’t actually infer any useful data on their own (aside from their underlying integral value).
Overreliance can often get you into a painful pattern of writing code like this:
public void SomeMethod(SomeEnum someEnum)
{
if (someEnum == SomeEnum.Value1)
{
// do stuff
}
else if (someEnum == SomeEnum.Value2)
{
// do other similar stuff
}
// etc etc
}
Which doesn’t scale well in the long run.
In this case, if you want to provide a particular image to a prefab instance, just reference the image via the inspector, and bypass the enum entirely. Use the object that you can about directly if you can, and if any additional data needs to accompany that object, create another object to encapsulate both. This is where scriptable objects can be very useful: Unity - Manual: ScriptableObject
Well, the “switch” statement in all programming languages runs very fast when number of cases is not big (less then 10). “Switch” is a simple “if” statement which in low level assembly is simply an JE or JNE assembly command. Comparing to maps (associative arrays), for example, switch branching is almost free for CPU if it is not looped many times. I do not know if Unity uses maps and how it works internally.
It’s not about performance, it’s about flexibility in your code. Enums make your code rigid, ergo, less flexible.
C# is an object oriented programming language. It is most flexible when used correctly in an object oriented fashion.
I agree that clasees with objects and methods give freedom of choice and OOP is better than writing in ancient C language with structs and functions, but in some situations enums are also good when something is hard-coded. We need more information from the topic starter to answer the question.
They already gave enough information and I already answered it. If they want to provide an image/sprite to a prefab, they can just reference the image/sprite directly via the inspector.