I am trying to make a simple 2d platformer endless running game using unity game engine also i am completely new to the unity game engine and c# scripting. Within the game i am using the instantiate for spawning the platforms. I managed to spawn gameobjects to the scene. My question is that how to find the previously spawned objects using c# script. it will be a great help if anyone provided the code. And sorry for my bad language
List<Object> existingOnes = new List<Object>();
var clone = Instantiate(...);
clone.name= "0001";
existingOnes.Add(clone);
var theOne = existingOnes.Where(item
=> item.name.Equals("0001").FirstOrDefault();
Note that "theOne" might no longer exist if you dynamically destroyed it.
If the clone is GameObject, you can also use:
GameObject.Find(...)
to get access to it.
Related
Im new to Unity and c#, I've been making a turn based game following one of Brackeys tutorial and i've added scriptable objects to it. Im looking to instantiate a random enemy everytime a fight starts.
Here's the lines that should be useful : ImageOfMyCode
The resources.LoadAll("Enemies") seems to work since I made 3 scriptable objects and the debug log also says 3.
Im really struggling past this to then shuffle allEnemies and instantite the randomly picked one.
Any help and guidance will be appreciated.
The error you get for the Instantiate is because you pass a number instead the object that you want to instantiate, you can read more about it here: Object.Instantiate
What you can do is the following:
var randomRange = Random.Range(0,allEnemies.Length);
GameObject enemyGO = Instatiate(allEnemies[randomRange],playerBattleStation) as GameObject;
I'm using the Method FindObjectsOfType inside Unity and I want to know what the order Unity find objects?
I tried to change the order of my game objects inside the hierarchy and even change the name of my game objects to 1_name, 2_otherName and still the list seems random.
Do it really random or there is an order for the search? There is no documentation about the order in the Unity website.
If someone really want, this is my relevent script:
[SerializeField] List<AreaMeshHandler> areaMeshHandlers;
void Awake()
{
areaMeshHandlers = FindObjectsOfType<AreaMeshHandler>(true).ToList();
}
Short answer, by InstanceID. can be seen on each GameObject in debug mode.
Tested by running this code in a scene with multiple GameObjects (some in hierarchy)
foreach (Target t in FindObjectsOfType<Target>())
Debug.Log($"{t.name}: {t.GetInstanceID()}");
After updating to Unity 2018.3.0f2 I`m unable to find a GameObjects prefab while the game is running. In the previous versions i was simply using this line:
GameObject prefabObject =
PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
But after the update this function only returns null, so I tried the new functions:
PrefabUtility.GetPrefabInstanceHandle
PrefabUtility.GetNearestPrefabInstanceRoot
PrefabUtility.GetOutermostPrefabInstanceRoot
but all of them return null but I`m sure that I am handing a prefab over as parameter. Any ideas what I am doing wrong here?
As soon as editor start playing (Application.isPlaying=true) prefab linkage with scene game objects will be broken (blue game objects turned into gray) and thus you cannot obtain prefab related information from it.
If you really need a scenario were you want to access such information on runtime, you should save it as Serialized variable in script component so that it will later available on runtime.
For example: this is a simplified contraption of what Mirror (Unity network plugin) is doing by issuing asset ID related stuff to help distinguish each prefab to spawn things in network on runtime.
[SerializeField] string m_AssetId;
void OnValidate() // Which will be called on build or editor play
{
#if UNITY_EDITOR
// Deposit UnityEditor API dependent into some field
m_AssetId = UnityEditor.AssetDatabase.GetAssetPath( gameObject );
#endif
}
Anyway, for running editor script, if you want to test or look for original prefab. UnityEditor.PrefabUtility is somewhat hard to find a full example of how to use them.
You can refer to my git repository on how to use them with examples.
https://github.com/wappenull/UnityPrefabTester
I’m trying to find a good way to play background music in Unity 3D. I want the music to keep playing consistently through scene loads. Don’t Destroy on load is fine and works, but every time I load the same scene, it makes another music game object because the scene itself has the game object in it. How can I solve my problem? I am a “beginner” (kind of), so I would like code I can understand.
I'd hands down recommend starting with an Asset like 'EazySoundManagerDemo'. It needs a little refactoring and refinement (ie it uses 3 arrays of audios with 3 sets of accessibility functions instead of one set with an AudioPurpose enum to increase code-reuse).
It does however solve the basic problem you have and is a good intro to using an audio manager / layer instead of simply playing audio directly from your GameObjects. Give that a shot, learn from it and then adapt it or create your own audio management layer.
Good Luck!
I recommend creating an audioSource object, then creating an script for this object and on the awake function do this:
void Awake() {
DontDestroyOnLoad(this.gameObject);
}
This will make the background music to keep playing between scenes. For more information you could use Unity's documentation about this function.
With help from a question on the unity forum, I think I have solved my problem. The link to the question is here...
https://answers.unity.com/questions/982403/how-to-not-duplicate-game-objects-on-dontdestroyon.html
The Best Answer is the one I’m using.
The code is this...
private static Player playerInstance;
void Awake(){
DontDestroyOnLoad(this);
if (playerInstance == null) {
playerInstance = this;
} else {
Destroy(gameObject); // Used Destroy instead of DestroyObject
}
}
I have just started using Unity and I am trying to put together a simple C# script that places the Prefabs (some 2D sprites) on pre-defined positions. The problem is, that whenever I apply the script to the prefabs and try to play the scene, Unity freezes and apparently generates an infinite loop that uses up all the memory (sometimes even giving me a black screen) and I have to force-kill the process in the task manager.
The code, however, is very simple and contains no loops at all:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DungeonTest : MonoBehaviour {
public Transform DungeonBuilder;
// Use this for initialization
void Start ()
{
Instantiate (DungeonBuilder, new Vector2 (1, 1), DungeonBuilder.rotation);
Instantiate (DungeonBuilder, new Vector2 (2, 2), DungeonBuilder.rotation);
Instantiate (DungeonBuilder, new Vector2 (3, 3), DungeonBuilder.rotation);
}
void Update()
{
}
}
It can be seen from the Hierarchy Window, that the Start() method creates several instances and the memory usage also goes up to 85%(!):
Unity infinite loop(?)
Please advise on what could have possibly gone wrong here. I have already watched several tutorial videos and I have read the relevant passages from the documentation, but I can't seem to figure this one out.
Thanks!
Your DungeonTest script should not be on the prefab you are instantiating. What's happening is that Start() gets executed every time the prefab gets instantiated.
So the first tile creates 3 new tiles. Each of those tiles now also make 3 new tiles and so forth to infinity.
Make a new object in the scene with the DungeonTile script and remove all scripts from the prefab you are instantiating.
This does not mean you can't have scripts on your prefab. Simply keep in mind that whatever is in your Start() method will execute as soon as your new instance is added to the scene.