- Home /
C# Utility Class
I'll admit that I'm completely new to C# and Unity3D. I am coming from an ActionScript 3.0 background, where I can create a class file that can then be instantiated from within other classes, as in:
var foo:Bar = new Bar();
Normally, I'd write a class to handle specific tasks, like loading and parsing an XML file, and I'd be able to instantiate it where needed to perform its duty. I'm trying to do the same with a tiny XMLParser class that I found on the forums here.
My question, then, is: How do I use this? I can't seem to just place it anywhere in the Project folder and instantiate it. Placing it in the Plugins folder or the Standard Assets folder makes no difference. I can't place it on a GameObject because it doesn't inherit from MonoBehavior, and I know that I could edit it to do so, but what's the point? If the code was provided like this I'm assuming that they wrote it to work this way, and I just have no idea how to use it properly.
So. I want to write a utility class, as in:
using UnityEngine;
using System.Collections;
class XMLParser {
XMLParser() { }
Foo ParseString(string xmlString) {
// parse
Foo parsedXML = Bar;
return parsedXML;
}
}
Is there something I'm totally missing on how to do this? or is this just not how Unity3D works?
I too am interested in this. The other night I was wanting something like a "Team", but it doesn't exactly make sense for it to make a GameObject because it's just an abstract association. Where and how would I get "$$anonymous$$m" code executed? (Like tracking kills, being responsible for relaying messages possibly. Things like that.)
Answer by sneftel · Jun 07, 2011 at 07:27 PM
You should just be able to put the .cs file anywhere in your Assets folder, and instantiate it (that is, new
it, not Object.Instantiate()
it) from within your own code. What error are you getting?
I was getting this: "error CS0122: 'X$$anonymous$$LParser.X$$anonymous$$LParser()' is inaccessible due to its protection level". I found that if I put "public" in front of the constructor and the ParseString method everything seems to work.
The .cs file is not in a special folder, and I am able to "new" it. Notice the "public" keywords that were missing from the original code I found:
using UnityEngine; using System.Collections;
class X$$anonymous$$LParser { public X$$anonymous$$LParser() { } public Foo ParseString(string xmlString) { // parse Foo parsedX$$anonymous$$L = Bar; return parsedX$$anonymous$$L; }
}
(Sorry about the formatting... couldn't see any way to do it in a comment)
Your answer
Follow this Question
Related Questions
Behind the scenes voodoo w/ Instantiate 2 Answers
Distribute terrain in zones 3 Answers
Instantiate class from other script but same gameObject 3 Answers
Multiple Cars not working 1 Answer