Hi.
How can I concatenate a string to form the name of a variable dynamically?
Example:
string number = "One";
void start()
{
// String ( myOne );
string my + number = "My number is One";
}
Thank You
Hi.
How can I concatenate a string to form the name of a variable dynamically?
Example:
string number = "One";
void start()
{
// String ( myOne );
string my + number = "My number is One";
}
Thank You
If you want to create a variable name dynamically, you can’t.
What is it you are trying to do exactly? I mean, your use case?
Hello BatmanDeveloper!
As Brathnann said, I’m not sure what you mean. Is this what you’re looking for?
sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class testString : MonoBehaviour
{
string my = "My ";
string number = " One";
string conString;
void Start ()
{
conString = my + "number is" + number;
Debug.Log (conString);
}
}
You can’t.
Variable names are determined at compile time in C#. You can maybe hack around this by using preprocessor directives, but that’s an amazingly bad idea, and besides like the others above posted, why would you want to do this?
I need to create a lot of variables dynamically to identify the objects on my scene and destroy it.
For example:
string myEnemyOne = GameObject.FindGameObjectWithTag(“myenemyone”);
string myEnemyTwo = GameObject.FindGameObjectWithTag(“myenemyotwo”);
string "my" + name = GameObject.FindGameObjectWithTag('"my' + name + '"');
Thank You
Either use a dictionary with the key as the name or use an array or list. Some sort of collection. The dictionary would allow you to find the objects by the name when you want to retrieve them.
You can’t do what you want to do.
+1 for a dictionary, being able to change variable names at runtime sounds like it would be a dreadful design decision and I hope that never ever becomes a thing.
ok, Thank You Everybody