- Home /
Creating an Object with a string C#! How?
Okay, so what I want to do is create a Tile everywhere there is an "X". so what I think i would do is:
var SectionOne: "XXXXXXXXXXXXXXXXXXX";
var SectionTwo: "XOOOOOOOOOOOOOOOXXX";
var SectionThree: "XOXXXXXXXXXXXXXOXXX";
var SectionFour: "XXXXXXXXXXXXXXXOXXX";
var SectionFive: "XOOOOOOOOOOOOOOOXXX";
var SectionSix: "XXXXXXXXXXXXXXXXXXX";
So I would instantiate a gameobject for every X but for "O" I would instantiate a wall... How do you do this?
Answer by syclamoth · Jan 08, 2012 at 11:13 AM
How about this- instead of using a string like that, why don't you use an array of booleans? (actually integers, since they're smaller...)
int[,] tiles = new int[,]{
{0,1,1,1,1},
{0,1,1,1,1},
{0,1,1,1,1}
};
Then, to instantiate objects over a space, do something like this-
for(int i; i < tiles.GetLength(0); ++i)
{
for(int j; j < tiles.GetLength(1); ++j)
{
if(tileSegments[i,j] != 0)
{
Instantiate(obj, new Vector3(i * tileWidth, 0, j * tileHeight), Quaternion.identity);
}
}
}
Please note that you can't assign these in the editor, or keep them serialised along with your other properties. You either have to hardcode them, or use a special custom editor.
(forgive incorrect syntax, I'm not fantastic at javascript. If someone who knows more than me can find any problems, please tell me!)
If you know C# Can you write that :) I'm trying to learn C# :)
Well, C# is basically like what I put there, but with some details changed. I'll change my answer to correct C#.
It didn't work :/ I keep getting lots of errors. Could you maybe try to fix it in an editor? You would help me soooo much! :D
Well, obviously that wasn't intended as completed code! It's really just a guide for what you need to do. What errors are you getting? You need to define a public GameObject 'obj' to use as the instantiated tile prefab.
Your answer
Follow this Question
Related Questions
How to Instantiate from correct Icon. 1 Answer
How to put gameObjects to the list? 4 Answers
MonoBehavior.Start() called infinite times? 1 Answer