- Home /
Question by
Justin113D · Jan 21, 2018 at 03:55 PM ·
c#getproperty
how do i get property by name out of an object?
so i have this class for example:
public class Sounds : Monobehaviour {
public AudioClip Click1;
public AudioClip Click2;
public AudioClip Click3;
}
Now, i wanna get one of the audioclips by name
public AudioClip getAudioClip (string name)
{
return Audioclip named name;
}
now i wanna get the audoclip click2 by entering "Click2", how do i do that?
Comment
Answer by WinterboltGames · Jan 21, 2018 at 04:08 PM
why not do this...
public class Sounds : MonoBehaviour
{
public AudioClip[] sounds;
public GetAudioClipByName(string name)
{
// if there's no sounds return null
if (sounds.length == 0)
{
return default(AudioClip);
}
// the for-loop way
for (int i = 0; i < sounds.Length; i++)
{
if (string.Compare(sounds[i].name, name) == 0) // string.Compare returns 0 if the 2 string are equal
{
return sounds[i];
}
}
// the foreach-loop way
foreach (AudioClip sound in sounds)
{
if (string.Compare(sound.name, name) == 0) // string.Compare returns 0 if the 2 string are equal
{
return sound;
}
}
}
}
Because Reflection is performance hungry!
do this...
public static object GetValue(object obj, string name)
{
return obj.GetType().GetProperty(name).GetValue(obj, null);
}
Yeah, i already did this, but still, is there a way to get the property by name? if you have more types than just "audioclip", then you cant put them all into a list
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to create Prefab with property 2 Answers
I want some ints stored in a new int right after eachother 1 Answer
problem with get{} and set{} 1 Answer