- Home /
Passing variables to generic component script
I have multiple scripts with the same variable URL, and I am trying to have one script that changes the scripts URL variable no matter witch script it is. But I am having trouble accessing the variable since a generic component wont have the variable. I'm trying to do something close to this if possible.
public GameObject obj;
public string URL;
public string type;
void start(){
var script = obj.GetComponent(type);
try{
script.url = URL;
}
}
Answer by SneakyLeprechaun · Jan 15, 2018 at 01:55 AM
What you can do is create a class that derives from a monobehaviour with the variable you would want to change, and then base all the classes you want to have that variable derive from that class instead of a monobehaviour
Creating an abstract classed as the base for all my scripts that contain the URL variable worked. Thank you, @SneakyLeprechaun
Answer by KittenSnipes · Jan 15, 2018 at 02:09 AM
I think that maybe this is what you are going for. Here is the main class:
string url;
public string getUrl()
{
return url;
}
public void setUrl(string newUrl)
{
url = newUrl;
}
Here is a class that references it and changes the original Url which I left Empty:
// This is the Url that I change the original url to
public string webUrl = "https://www.youtube.com";
// The main url class reference
WebUrl urlSetter;
void Start()
{
// I get the main class that should be attached to the main object
urlSetter = GetComponent<WebUrl>();
}
void Update () {
Debug.Log("Original Url is Empty: " + urlSetter.getUrl());
// I set the url here
urlSetter.setUrl(webUrl);
Debug.Log("New Url: " + urlSetter.getUrl());
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612150516im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
differences: generic GetComponent. 3 Answers
Count returning 0 when called outside object~ 1 Answer
Generic MonoBehaviour with nested class serialization issue 1 Answer
Initialize UnityEvent via script 1 Answer
Why can't I use a variable of the same type as a static generic variable when using foreach? 2 Answers