Why the property Range not exist in Random class in unity? - c#

using System;
using UnityEngine;
using System.Collections;
using UnityStandardAssets.Characters.ThirdPerson;
public class Multiple_objects : MonoBehaviour {
public GameObject prefab;
public GameObject[] gos;
public int NumberOfObjects;
private ThirdPersonCharacter[] thirdPersonCharacter;
private Animator[] _animator;
private int count = 0;
void Awake()
{
Vector3 v3 = prefab.transform.position;
_animator = new Animator[NumberOfObjects];
gos = new GameObject[NumberOfObjects];
for(int i = 0; i < gos.Length; i++)
{
count = count + 2;
GameObject clone = (GameObject)Instantiate(prefab, Vector3.zero, Quaternion.identity);
gos [i] = clone;
gos [i].transform.position = new Vector3 (v3.x - count, v3.y, v3.z);
_animator [i] = gos[i].GetComponent<Animator> ();
Math.Round(Random
When i type point after the Random like: Random.
I have only Equals and ReferenceEquals
And if i create a variable of Random for example:
Random _random;
Then i type _random.
I get more propeties but not Range.

You are using both the UnityEngine and System namespace. Both of these namespaces contain a Random class, so Visual Studio/Unity doesn't know which one you want to use. To specify which random you want to use, you would simply do this:
UnityEngine.Random.Range(0.0f, 5.0f);

Write UnityEngine.Random.Range
You have to clarify the namespace.
Unless you want the .net Random ( in that case look at the other answer)

Why the property Range not exist in Random class in unity?
Random _random;
_random.Rand...
Range is a static function in the Random class. You don't need to create instance of the class to use static functions inside then. You call static functions directly.
This should do it: Random.Range(0f,3f);
If you are getting the Random' is an ambiguous reference betweenSystem.Random' and UnityEngine.Random' error then that's because you haveusing System;`(which you did in your code) and therefore you must use the full namespace to access Unity random function.
UnityEngine.Random.Range(0f, 3f);

Related

how to Pick random GameObject in Unity

I'm making an endless runner game, and I have 4 types of terrain I want to auto-generate.
the auto-generation works, but I want to select a random terrain but I can't figure out how.
I have tried this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformManager: MonoBehaviour
{
[SerializeField]
private GameObject[] _platformPrefabs;
[SerializeField]
private int _zedOffset;
// Start is called before the first frame update
void Start()
{
randomTerrain();
}
public void RecyclePlatform(GameObject Platform)
{
Platform.transform.position = new Vector3(0, 0, _zedOffset);
_zedOffset += 12;
}
public void randomTerrain()
{
for (int i = 0; i < _platformPrefabs.Length; i++)
{
Instantiate(_platformPrefabs[Random.Range(0, 3)], new Vector3(0, 0, i * 12), Quaternion.Euler(0, 90, 0));
_zedOffset += 12;
}
}
}
but it only selects the first game object every time except the first initiation. how can I make it select randomly?
The random number generator is not really random; it only generates a pseudo-random stream based on a given seed. If this seed isn't initialized, that could explain why you're getting the same result each time. To initialize the random state you'll need to use Random.InitState.
A typical approach is to use the system clock for random number generators. Games like Minecraft actually let you specify this seed so that the same seed = the same randomly generated content.
Random.InitState(System.DateTime.Now.Ticks);

Unity-C# Instantiate is not working

I use instantiate to create objects but it create object continuous.
Code is here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class instantiateObject: MonoBehaviour {
public int topSayi;
public Transform prefab;
void Start () {
for(int a = 0; a < topSayi; a++)
{
prefab.localPosition = new Vector3(0, a * -0.5f, 5);
Instantiate(prefab);
}
}
}
it create object continuous
It looks like it does not go inside the for loop. I would guess topSayi is the times you want to instantiate, so you wrote the for statement wrong. It should be like this:
for(int a = 0; a < topSayi; a++)
{
prefab.localPosition = new Vector3(0, a * -0.5f, 5);
Instantiate(prefab);
}
You were checking if a is bigger than topSayi, which would never be the case. therefore it will never go inside the for statement. It must be the other way around.
Revision 1:
Having a script on a prefab that creates a copy of that same prefab in either Start() or Awake() is the functional equivalent of creating an infinite recursion. Whenever a copy of the prefab is instantiated, it (almost) immediately creates another copy of itself ad infinitum. Simply put, don't do this! Have some other manager-type object to do the instantiating.
Original:
You don't instantiate transforms, you instantiate GameObjects:
public GameObject prefab;
Secondly, you should set the position AFTER or, preferably, during instantiation:
var go = Instantiate(prefab, position);
And finally, as #JackMini36 noted, the condition on your for loop is (edit: was) malformed:
for(int a = 0; a < numSayi; a++)

Automatically add all declared class variables to list

I am trying to automatically list all declared variables on my class. I am working on a pooling script, so for each gameobject I have a prefab, an array, an array size and a pool size. (they all follow naming standards, prefab name + "array" for array and etc).
private GameObject _PlayerLaserPrefab;
private GameObject[] _PlayerLaserPrefabArray;
private int _PlayerLaserPrefabPoolsize = 30;
private Queue<Transform> _PlayerLaserPrefabQueue = new Queue<Transform>();
private void Initiate_PlayerLaserPrefabPool()
{
_PlayerLaserPrefabArray = new GameObject[_PlayerLaserPrefabPoolsize];
for (int i = 0; i < _PlayerLaserPrefabPoolsize; i++)
{
_
PlayerLaserPrefabArray[i] = Instantiate(_PlayerLaserPrefab,Vector3.zero,
Quaternion.identity) as GameObject;
Transform Obj=PlayerLaserPrefabArray[i].GetComponent<Transform>();
ObjTransform1.parent = transform;
_PlayerLaserPrefabQueue.Enqueue(ObjTransform1);
_PlayerLaserPrefabArray[i].SetActive(false);
}
}
this code has to be repeated for all game´s objects so I am looking for a method to dynamically generate these funcions and variables based on the object´s name.
//pseudo code would be:
foreach (gameobject in list)
create array
create queue
initiate pool
Generate spawn function

How do i check if 2 Lists have the same Sprites in c#

the question is, how do i compare two lists of the same type(in this case Sprite) and check if they are equal.
To get into my code, i have GameObjects symbol, shadow and cable and those change their sprite with a buttonclick(different script). On the other hand i have GameObject[] and i already have GameObjects inserted. Now i make a Dictionary with GameObject as key and a specific List of Sprites as value, i search for a key and return the value into List ActualList and compare that with a List composed of the current sprites of GameObjects symbol, shadow, cable.
My Problem is tho that its not applying RigidBody to the GameObject, so the if statement seems to not work. Is there maybe a different way to compare two lists.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class Rigi : MonoBehaviour
{
public GameObject[] Akkus;
public Button Generator;
public GameObject symbol, shadow, cable;
int count1;
public Sprite[] spriteSymbols, spriteShadows, spriteCables;
public Dictionary<GameObject, List<Sprite>> AkkuDic = new
Dictionary<GameObject, List<Sprite>>();
public List<Sprite> ActualList = new List<Sprite>();
public void On_Click_Button1()
{
List<Sprite> CompareList = new List<Sprite>();
CompareList.Add(symbol.GetComponent<SpriteRenderer>().sprite);
CompareList.Add(shadow.GetComponent<SpriteRenderer>().sprite);
CompareList.Add(cable.GetComponent<SpriteRenderer>().sprite);
AkkuDic.TryGetValue(Akkus[count1], out ActualList);
if(ActualList.SequenceEqual(CompareList))
{
Rigidbody RigidbodyGameobject =
Akkus[count1].AddComponent<Rigidbody>();
}
}
public void Awake()
{
List<Sprite> mySpritesWind = new List<Sprite>();
mySpritesWind.Add(spriteSymbols[5]);
mySpritesWind.Add(spriteShadows[0]);
mySpritesWind.Add(spriteCables[0]);
List<Sprite> mySpritesOel = new List<Sprite>();
mySpritesOel.Add(spriteSymbols[4]);
mySpritesOel.Add(spriteShadows[2]);
mySpritesOel.Add(spriteCables[1]);
List<Sprite> mySpritesWasser = new List<Sprite>();
mySpritesWind.Add(spriteSymbols[5]);
mySpritesWind.Add(spriteShadows[0]);
mySpritesWind.Add(spriteCables[0]);
List<Sprite> mySpritesSolar = new List<Sprite>();
mySpritesWind.Add(spriteSymbols[3]);
mySpritesWind.Add(spriteShadows[5]);
mySpritesWind.Add(spriteCables[0]);
List<Sprite> mySpritesKern = new List<Sprite>();
mySpritesWind.Add(spriteSymbols[1]);
mySpritesWind.Add(spriteShadows[1]);
mySpritesWind.Add(spriteCables[1]);
List<Sprite> mySpritesKohle = new List<Sprite>();
mySpritesWind.Add(spriteSymbols[2]);
mySpritesWind.Add(spriteShadows[4]);
mySpritesWind.Add(spriteCables[1]);
AkkuDic.Add(Akkus[0], mySpritesWind);
AkkuDic.Add(Akkus[1], mySpritesOel);
AkkuDic.Add(Akkus[2], mySpritesWasser);
AkkuDic.Add(Akkus[3], mySpritesSolar);
AkkuDic.Add(Akkus[4], mySpritesKern);
AkkuDic.Add(Akkus[5], mySpritesKohle);
}
}
The default comparer used in SequenceEqual will check to see if the reference pointer of the class instance of Sprite in CompareList is the same "memory reference pointer" as is stored in ActualList. Without seeing the full lifecycle of this we cannot be sure, but if the GetComponent() ever creates a new instance of the class Sprite your code will not work as expected. If I remember Unity, it may well create a new instance or return a cached instance.
I expect you need to compare some property (like AssetID or other unique value of the sprite) between the lists, no the list reference pointers themselves; especially if you are not in complete control of the Sprite class life history within the application and you are using someone elses Factory (i.e. GetComponent)

spawn obstacles c# and accessing from another script

I'm Getting a error when i try to instantiate in the manager class. saying
Error CS1061: Type UnityEngine.Object' does not contain a definition forGetComponent' and no extension method GetComponent' of typeUnityEngine.Object' could be found. Are you missing an assembly reference? (CS1061) (Assembly-CSharp)
Add this to your Obstacle class:
void Start()
{
manager = GameObject.FindWithTag("ObstacleManager").GetComponent<ObstacleManager>();
}
The tag obviously has to be the tag of the gameobject the manager is attached to.
Also: Always start class names with a capital letter (I did that in the snippet, keep that in mind, you will get an error right know with that).
Maybe you want to actually change your spawning a bit though. Have two lists, one for free spawnpoints and one for occupied. When you destroy an obstacle, pass the position to the spawning function to move the position to the free list.
Edit:
Another option to create the reference is to set it in your ObstacleManager on spawning. You need to grab a reference to the instantiated obstacle for this. I believe this should work without actually grabbing the obstacle gameobject, but you could do that too.
Obstacle obs = ((GameObject)Instantiate(TypeOfObstacles[j], pointsAvailiable[pointsIndex].position, Quaternion.identity)).GetComponent<Obstacle>();
obs.SetManagerReference(this);
And in Obstacle add
public void SetManagerReference(ObstacleManager obsManager)
{
manager = obsManager;
}
For the free position you can do something like this:
// in Obstacle.cs
public void OnMouseDown()
{
manager.SpawnNewObstacle(transform.position); // you might be able to actually pass the transform, but I'm not sure if it will get destroyed before used in the other function
Destroy(gameObject);
}
In the Manager:
public int noOfObsacles;
public float[] xPercent;
public GameObject[] TypeOfObstacles;
float y;
// to keep track of which spawn points are free and which aren't use these lists
private List<Transform> freePositions;
private List<Transform> occupiedPositions;
private void Start()
{
freePositions = new List<Transform>(spawnPoints);
occupiedPositions = new List<Transform>();
SpawnObstacles();
}
private void SpawnObstacles()
{
// just use this for initial obstacles
// call Spawn as often as needed
for(int i = 0; i < noOfObstacles; i++)
{
Spawn();
}
}
// you call this function from the obstacle that gets destroyed
public void SpawnNewObstacle(Vector3 freePos)
{
// find the spawnpoint in the occupied points
// and move it to the free ones since the obstacle got destroyed
for(int i = 0; i < occupiedPositions.Count; i++)
{
if(occupiedPositions[i].position == freePos)
{
freePositions.Add(occupiedPositions[i]);
occupiedPositions.RemoveAt(i);
break;
}
}
// and call Spawn
Spawn();
}
private void Spawn()
{
y = Random.value;
int pointsIndex = Random.Range (0, freePositions.Count);
for (int j =0; j<xPercent.Length; j++)
{
if ( y < xPercent[j])
{
// these 4 lines are essential for the spawning
Obstacle obs = ((GameObject)Instantiate(TypeOfObstacles[j], freePositions[pointsIndex], Quaternion.identity).GetComponent<Obstacle>();
obs.SetManagerReference(this);
occupiedPositions.Add(freePositions[pointsIndex]);
freePositions.RemoveAt(pointsIndex);
break;
}
}
}
had a bracket issue! my bad
obstacle obs = ((GameObject)Instantiate(TypeOfObstacles[j], freePositions[pointsIndex].position, Quaternion.identity)).GetComponent();

Categories