Game Development Asked by Stormzy18 on December 1, 2021
I want to use a string to reference a gameobject that I already have in my code, but the console says that you can’t convert a string to unityengine.object. I have a string that says aaaa
and a gameobject that has the name aaaa
.
using System.Collections.Generic;
using UnityEngine;
public class WorldRenderer : MonoBehaviour
{
public Transform Tile;
string seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacaaabaaaaaaaa";
public int worldHeight;
public int worldWidth;
private int seedSub = 0;
public GameObject aaaa;
public GameObject aaab;
public GameObject aaac;
void Start()
{
transform.position = new Vector3(worldWidth / 2 * -0.64f + 0.32f, worldHeight / 2 * 0.64f + 0.32f);
for (int height = 0; height < worldHeight; height++)
{
transform.position = new Vector3(worldWidth / 2 * -0.64f - 0.32f, transform.position.y);
transform.position = transform.position - new Vector3(0, 0.64f);
for (int width = 0; width < worldWidth; width++)
{
seedSub = seedSub + 1;
transform.position = transform.position + new Vector3(0.64f, 0);
//Here's the problem VVV
GameObject tilepos = Instantiate(seed.Substring(seedSub * 4 - 3, 4)) as GameObject;
//Here's the problem ^^^
tilepos.transform.position = new Vector2(transform.position.x, transform.position.y);
}
}
}
}```
I looks like you want to match not the game object name, but the name of your variable. You can do that with a dictionary, something like this:
void Start() {
var patternMatch = Dictionary<string, GameObject>(3);
// Add each of your game objects into a collection, with their string as a key.
patternMatch.Add("aaaa", aaaa);
patternMatch.Add("aaab", aaab);
patternMatch.Add("aaac", aaac);
//...then later, inside your for loop...
// Form the key you want to search for.
string key = seed.Substring(seedSub * 4 - 3, 4);
// Look for a matching entry in your dictionary, and error if missing.
if(!patternMatch.TryGetValue(key, out GameObject prefab)) {
Debug.LogErrorFormat("Could not find matching prefab for pattern "{0}"", key);
continue;
}
// Now we can use the object we looked up.
GameObject tile = Instantiate(prefab,
new Vector3(transform.position.x, transform.position.y),
Quaternion.Identity);
// ...end of your loop
}
Answered by DMGregory on December 1, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP