How to randomize what scriptable object gets loaded - c#

I am a complete noob when it comes to coding in unity . I have a couple of different enemies that are scriptable objects and when I start a battle I would like to load a random one of those enemies. Can anyone please help I cant figure out how to do it.

It depends on what you have. Are you loading Scriptable Objects from the Resources folder? If you are, you may use Object[] enemies = Resources.LoadAll("Enemies", typeof(Enemy)). This code will load everything of a type "Enemy" from a folder "Resources/Enemies/". Then you can get random numbers from 0 to enemies.Length and get an object from the array using the number as an index

Related

How to instantiate a randomly picked ScriptableObject?

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;

Reading from file more efficient than GameObject.Find?

Hey I'm new to Unity and I started creating a Tower defense game. Currently I can create one level and have monsters spawn and walk along a path I made with empty GameObjects ( Waypoints ). I can also drag and drop Heroes onto certain places called ( PlacePoints ); these are empty GameObjects, too. Here is a picture of my Level_1 prefab:
Level_1
This all works well so far but I read about GameObject.Find and Transform.Find being slow. And since I want to write fast and clean code right from the start, how would I make this faster and more efficient? Here is an example from my LevelManager script:
public Transform findPlacePoints()
{
return GameObject.Find("Level_1(Clone)").transform.Find("PlacePoints");
}
The question is, would it be faster to store all the information in a .txt file and load it in my LevelManager and then have each Script find the LevelManager which is a Singleton and ask for specific information? Basicly have the LevelManager act as a distributer? Informtion would be:
Spawn Times
Positions of ( SpawnPoints, Waypoints, PlacePoints, etc.)
Enemy Types
Don't fall into the trap of Premature Optimization. GameObject.Find is only slow if you make it slow (searching lots of objects in your scene). Check out the Improving Performance of Our Code section of Unity's Optimizing Scripts in Unity Games if you want to learn what writing good patterns looks like in Unity. It should provide you with some tips and not have to worry about deep-diving into GameObject.Find and disk operation optimizations.
As stated, It really depends on how many items you are searching and how you write the code. From my understanding direct references, such as setting a variable in the inspector, is the most efficient way to "find" something in scene.
Unless you are doing it a lot and in updates, it really shouldn't hurt performance that much. I would focus my optimization time on not destroying/instantiating, keeping UI updates out of the game loop, and keeping light scripts on frequently used objects.
Hope this helps!
What I would do (not saying it is the best) is have a static class just to store some informations (not a monobehaviour) let say Utilities. Have a public GameObject[] waypoints in it. On each of your level, add a script that will overwrite Utilities.waypoints with it's own GameObject[] variable. In the inspector, just drag/drop your waypoints on this script. You can then call Destroy(this) which will delete only the script after completion.

Why is my transform.position setter called via OnMouseDown() so slow?

I have the following method in my code:
private void OnMouseDown()
{
cube.transform.position = new Vector3(0, 1, 0);
}
When clicked on the gameObject, this method is called. It takes long to change the position of the cube (not more than a second, but still long, at least half a second). It does affect the user playing experience.
If I don't change the position of the cube, but for example its material, it is still slow. So I do know that this doesn't have to do with the line in my OnMouseDown() event.
Note however that I do have around 35 imported 3D meshes in my Scene, as well as over 50 primitive game objects. Does this have anything to do with the method being slow? Because when I make an empty Unity project with just 2 gameObjects, the method is fast.
Is it because of my full scene? Any ideas? Thanks!
If someone knows how to speed it up as well, I'd love to know!
EDIT: If I remove all my 3D meshes, the method is fast...
Unless your transfom tree is hundereds of children deep, this should be pretty much instant, its one of the things Unity has been designed to do quickly, so I think this has to do with the meshes you import. The should not have too many verticies, too many materials, and too many objects.
You can try to go through you objects with a 3D editor package (blender?) and combine the chunks into single objects.
If unity lags when you move an object, it may mean it has too many individual transforms to process. If your scene is intense you can gain a lot of performance by 'baknig' it, combining individual objects into larger meshes (those live on the gpu and cost gpu time not cpu time).
It is also possible that one or more of the meshes you imported has too many verts/triangles. If you currently have 10fps you may want to target having lighter meshes, and as few seperate GameObjects as possible (ideally you want the environment to be just a few combined meshes (to enable culling), not thousands of objects)
solution
Try to check if there are heavy materials are used that can slow the procedure. The game becomes slow when the objects are being added in the project and it destroy the overall efficiency of the game . It happens with me when i used too heavy models in the project the overall speed of the game is decreased . I replaced them with lightweight models of truck and issue was resolved .

Unity Figure out the type of an object in scene

I am working with a scene that was created by someone else.
There are some objects in the scene that I need to dynamically reference from a script, but I can't figure out their type.
This might sound dumb, but I can't find any "properties", and the inspector doesn't seem to tell me the type of the selected object, just what components are in it.
So how can I find what Type it is, so that I can use
Component.FindObjectsByType<T>()
in scripts to get it (and a few others that are the same type)?
EDIT: I am using C#, but I am looking for a way, from the scene editor, to find the type of a specific object, so that I can use that type later when I'm writing scripts. For example, some objects are Terrains, Sprites, Cubes, etc.
All objects in the scene are of type GameObject. What you are searching for are components. You can learn about components and how they work here in documentation.
If you want to access methods and variables of a component, you can do it multiple ways.
If you want to access a component of a GameObject, you can do it like this:
SpriteRenderer sprite = gameObject.GetComponent<SpriteRenderer>();
If you want to get all components of some type in the scene, you can do it like this:
CharacterController[] controller = FindObjectsOfType<CharacterController>();

Infinite Road Update

I am working on Unity for a month. I am new on Unity and C#, before Unity I worked other game engines. Whatever I am working on infinite run game, I wrote random road generator. Road generator is working well but I have problem about updating road. I can update road manualy like this. How can I update it automaticly?
void Update()
{
if(Input.GetKeyDown(KeyCode.A)) UpdateRoad();
}
My UpdateRoad method adding road like this(I am using object pooling).
I want to update after Link Road, OnExitTrigger or something I dont know. How can I do it?
You would need to implement Object Pooling.
I would suggest making your Design of Objects first so you can test. Or if not use, the stock Blocks Primitive of Unity3D as your Prefabs. I hope you already know prefabs. It is a major key for making infinite runner. Actually a main core for making any kinds of game.
Prefabs is an Object File where you can Instantiate it in a location. So lets say you will generate a Flat walkable, then Generate a Pit. You would probably want to stack them together.
Now Generating them is easy. You would not like to go in an Update? Approach because most likely you're not going to update, but you're going to further stack what is going on ahead, based on your game logic.
To further Understand this, Unity3D already made a project or Fully Detailed tutorial. It maybe made in 2D but it is going to be the same, if you're going to change the Collider2D to Collider <- this is important in your case.
https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/infinite-runner
Update
You would need to create an Object, that is invisible. Meaning a Trigger.
Then on Trigger call your method UpdateRoad();
https://unity3d.com/learn/tutorials/modules/beginner/physics/colliders-as-triggers
Detailed Videos about Trigger.
If I understood your needs correctly, you could create Empty Object name it SpawnPoint, set position for Spawn Point as you need (out of the camera view) and then Instanciate random prefabs of road. Concerning On TriggerExit - it could be used to destroy "old piece of road". But to have it working properly, dont forget to set collider and rigitbody to your objects. Dont add collider2D or Rigitbody2d, add and use Box Collider and Rigitbody components

Categories