- Home /
C# How to get/access List from another script
Hi,
I'm new with scripting and C#, and hope someone can help me with this issue.
I have a List in script PlayerKnowledge, but I want to access it and read through the List in script PlayerAttack, but I keep getting errors.
What I'm basically trying to do is to see if enemyName exists in the List, and if so do an action. I've tried a bit with getComponent etc, but no luck. This is my latest attempt with a getter method instead:
//This is the first script
public class PlayerAttack : MonoBehaviour {
private PlayerKnowledge playerKnowledge;
private List<string> knowledge;
// Use this for initialization
void Start () {
var knowledge = new List<string>();
PlayerKnowledge playerKnowledge = GetComponent<PlayerKnowledge>();
knowledge = playerKnowledge.getKnowledge();
}
//This is the second script
public class PlayerKnowledge : MonoBehaviour {
public static List<string> knownNames;
// Use this for initialization
void Start () {
knownNames = new List<string>();
}
public string getKnowledge() {
return knownNames;
}
// Use this for initialization void Start () { var knowledge = new List(); PlayerKnowledge playerKnowledge = GetComponent(); knowledge = playerKnowledge.getKnowledge(); }
Which gives me this: error CS0029: Cannot implicitly convert type `string' to `System.Collections.Generic.List'
Anyone who sees a solution?
It looks to me like you've got you head messed up around statics and using GetComponent - check out this overview and this tutorial on Unity Gems.
You define this:
public string get$$anonymous$$nowledge()
{
return knownNames;
}
But knownNames is a list of strings and not a string itself - what string are you hoping to retrieve?
I was actually trying to retrieve the List, so that I could go through it and see if string x was in there :P
Answer by AeonIxion · Oct 26, 2012 at 06:29 AM
public string getKnowledge() {
return knownNames;
}
you're returning knownNames, which is a list of strings, but the returnvalue of your method is set to string.
try:
public List<string> getKnowledge() {
return knownNames;
}
also, I'm wondering why you want to copy the knownNames list into another list. knownNames is public so you can just access it with playerKnowledge.knownNames, no?
it worked! Great, thanks! Was sure I'd tried it earlier, probably a typo then embarassed
What if you want to return a complex list(ints, strings, bools) rather than primitives?
Your answer
Follow this Question
Related Questions
How to access List<> from other script? 1 Answer
Last time I'll ask for help on this lol 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How Do I Access and Change Items in a List on Another Script? 2 Answers