how to get script by string

hi guys is there a way i can make a public string and change the script that i need to get?

GameObject parent = transform.parent.gameObject;
SpiderScript SpiderS = parent.GetComponent ();

how can i change the “spider script” using public string or some other public?

i want to make a universal health bar and it won’t be universal without this

or i should make universal health script that control health and leave it as is?

Seems like an inheritance question? http://www.dotnetperls.com/inheritance first example?

Could you perhaps use that approach instead?

1 Like

Using strings for GetComponent slows down your game.

I would use the inheritance for that when you inhert from a Class that inherts from a MonoBehaviour and hat the [Serializable] Attribute before the class header you can add the Script to the Editor. In the Script where you want to use your Script I would make a public field with the Type of the Base Class so you that you can set all derived Classes in the Editor for this Field.

Then the code is cleaner.

public abstract class UniversalScript : MonoBehaviour{

public virtual SomeMethod( ){
}

}
[Serializable]
public class SpiderScript : UniversalScript{

}
public class SomeScript : MonoBehaviour{

public UniversalScript uniScript;

void Update(){
uniScript.SomeMethod();
}

}
3 Likes

thanks for the answers guys but it seems to complicated for me atm I’m a real beginner and to do as mentioned i need to change the whole game.

for future generation use what posters above said and if not create script that only contains public float health and attach it to anything that have a health and reference that float from the other “on hit” or what ever script name.

The answer from @Mabenan was about as close to perfect as you get.

Good luck

This Worked Great For Me !
Thanks :slight_smile: