Access to other GameObject attribute using string?

Hi,
I’ve just stuck with one dummy problem…

(TargetObject):

public class MainScript : MonoBehaviour
{
public AudioSource Sound1;
}

So what I want is to get Sound1.volume from other Object using string name ‘Sound1’;

var target = GameObject.FInd(“TargetObject”).getComponent();

So I have access to MainScript but how to call Sound1 if I have just string ‘Sound1’ ? Is it possible to convert it to match Sound1?

Thanks in advance!

While you can find a field by its name, it is something you don’t really want to do as it is not exactly fast, and indicates a flaw in the logic of your code. This kind of thing also creates “landmine” type of bug which lays undiscovered until someone accidentally triggers it at runtime, which is not a good thing.

So, you REALLY should just access “getComponent().Sound1”.

If that isn’t enough, you should step back and think what you’re trying to do.

2 Likes

I want to set attribute name via Inspector as string and use this string to decrease attribute volume.
Your way is works “getComponent().Sound1”.
but when I use:

public string mySound = Sound1;

then I can’t make it works. Is there any way to do it?

You are trying to set a string to the value of an AudioSource. They are completely different things, so no it will not work.

Why are you trying to use the string to increase or decrease volume? Why not just actually adjust the volume (float) rather than this really strange round-about way of doing things?

It may looks strange. The Reason why I’m doing it:

  • I have GameObject Audio with all my AudioSources attributes (around 30). I’m using it to play sounds ect
  • I’ve created another audio trigger and I want to easy point my audio which one need to be turned on/off or even volume changed. I thought I can do it just putting AudioSources name

Can’t do that, because .Sound1 is an AudioClip, and you’re trying to assign a string to it.

Store the reference to the clip you want to play in the trigger.

Also, read about AudioSource.PlayClipAtPoint

To get the name of an AudioSource:
string soundName = Sound1.name;

To set the name of an AudioSource:
Sound1.name = "whatever";