I'm looking for a way to find all CubeGameObject in the scene. I'm trying to do this :
Cube[] ballsUp = FindObjectsOfType (typeof(Cube)) as Cube[];
But cube isn't a game object type apparently.
I think i need to use something related to PrimitiveType but can figure out what and how to use it...
Thanks
Your Cube is of primitive type. And Primitive type objects are not possible to find using FindObjectsOfType.
There are many ways to solve the above problem. The easiest is by using tags.
When you instantiate your cube object you can use tag "Cube".
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.tag = "Cube";
Then you can get all the cube objects in scene with cube tags using
GameObject[] arrayofcubes = GameObject.FindGameObjectsWithTag("Cube");
This will give all the array of GameObject cubes in the scene.
FindObjectsOfType can be used to find gameobjects with attached classed and not primitive types.
Another way to proceed is finding all objects with MeshFilters and Searching for the Desired primitive name in the mesh filter arrays
string[] meshNames = new string[5] {"Cube", "Sphere", "Capsule", "Cylinder", "Plane"};
MeshFilter[] allMeshFilters = FindObjectsOfType(typeof(MeshFilter)) as MeshFilter[];
foreach(MeshFilter thisMeshFilter in allMeshFilters)
{
foreach(string primName in meshNames)
{
if (primName == thisMeshFilter.sharedMesh.name)
{
Debug.Log("Found a primitive of type: " + primName);
}
}
}
Geeting all the Object by their primitive type (C#)
You could try using a script. Let's say your GameObjects have a script MyScript, then you could FindObjectsofType GameObject and GetComponent Myscript.
Hope this helps. Although, I know it's not the answer you want, it's definitely an idea worth trying as a last resort :)
You could try this. If you are using the cube primitive of unity the mesh should be called "Cube" and while running "Cube Instance".
var gameOjects = GameObject.FindObjectsOfType<GameObject>();
foreach (var gameOject in gameOjects)
{
var meshFilter = gameOject.GetComponent<MeshFilter>();
if (meshFilter != null && meshFilter.mesh.name == "Cube Instance")
Debug.Log(gameOject.name);
}
tough this isn't very elegant or robust.
A more appropriate way would be to tag all cubes and get them by "FindGameObjectsWithTag"
Then recommended way from Unity of doing this is to create a tag and then use GameObject.FindGameObjectsWithTag to find all of them. GameObject.FindGameObjectsWithTag returns array of objects in this tag.
For example, create a tag called "cubeTags" then go to each cube and change the tag to cubeTags. When you want to find all the cubes, you can just do:
GameObject[] cubes = GameObject.FindGameObjectsWithTag ("cubeTags");
Cube[] ballsUp = new Cube[cubes.Length];
for(int i=0; i<cubes.Length; i++){
ballsUp = cubes[i].GetComponent<Cube>();
}
Related
Could you please help me to write the right syntax? I am stuck with the following code:
GameObject cube = (GameObject)Instantiate(cube_prefab, new Vector3(x, y, 0), Quaternion.identity, transform);
cube.GetComponentInChildren<TextMeshPro>.text = "test" **// WORKS FINE**
Take into account that inside my prefab i have more TextMeshPro, so my question is: how can I get to the second object if i can't access trought an array ? sounds weird for me
cube.transform.GetChild(0).GetComponent<TextMeshPro>().text = "AAA" // DOESN'T WORK
Thanks in advance
The GetChild(int) method is a method of transform. In your example, you're calling GetChild(0) from the GameObject instead. So the fix in your example would use the transform property of your "cube", find the child, then get the component of the child item:
GameObject cube = (GameObject)Instantiate(cube_prefab, new Vector3(x, y, 0), Quaternion.identity, transform);
cube.GetComponentInChildren<TextMeshPro>.text = "test" **// WORKS FINE**
cube.transform.GetChild(0).GetComponent<TextMeshPro>.text = "test"
Here's the Unity docs for GetChild(int).
If you wanted to iterate over the next level of children for your game object, you could do this:
var t = cube.transform;
var childCount = t.childCount;
for ( int i = 0; i < childCount; i++ )
{
if ( t.GetChild(i).TryGetComponent<TextMeshPro> ( out var tmp ) )
{
tmp.text = $"TextMeshPro found on child {i}";
}
}
Be aware, that this will only iterate over the direct children of "cube", not the children of those children. You would have to check the child count of each child to check further down the family tree.
Sorry if I sound like I'm preaching, but it seems you just try to guess what the syntax is, without knowing what it each thing really does, and it won't do you any good. You should look into methods with generics (especially how to call them) and try to write code meaningfully instead of throwing brackets here and there, and expect things to happen.
With that out of the way, let's look at your issue.
The name 'GetChild' does not exist in the current context, because your cube is of GameObject type, which indeed doesn't have a GetChild method. The component that does have it is Transform. You should call it like: cube.transform.GetChild(0)...
If you fix that, the next issue is that GetChild method doesn't use generics (<Type>) and even if it did, first you provide should provide a type in angle brackets, and then write regular brackets () to indicate method call. What you probably wanted is to first get child, and then to get a component in it: cube.transform.GetChild(0).GetComponent<TextMeshPro>().text = "test";
In cube.GetComponentInChildren<TextMeshPro>.GetChild(0).text you miss brackets: cube.GetComponentInChildren<TextMeshPro>().GetChild(0).text. Morover, the TextMeshPro doesn't have a GetChild method, you must have confused ordering of your method calls.
In cube.GetComponentInChildren<TextMeshPro>[0] you try to use syntax as if you were using arrays, while GetComponentInChildren is just a method, not a property that is an array.
To answer your question shortly: use yourGameObject.transform.GetChild(childIndex).GetComponent<TextMeshPro>().text transform.GetChild() to navigate down to your desired gameObject and only then call GetComponent (remember brackets!) to get to your text property.
the right syntax was
cube.transform.GetChild(0).gameObject.GetComponent().text = "test"
cube.transform.GetChild(1).gameObject.GetComponent().text = "test"
I've been trying to get a script working to check if my player is below a certain Y lvl, for a platformer. so it can be respawned to the beginning, But how do I put the y lvl inside a variable to check it? i cant figure it out lol
In the Update() run something like:
if(player.transform.position.y < 1)
{
//do something
}
where 'player' is the GameObject in question.
I am assuming you want to just want to compare (==, <=, >=, all that jazz is what I mean by comparing just in case you were not aware) the Y value to something like 10 for example. This is easy and you don't even need a variable necessarily for this.
//For the object position relative to the world
if(transform.position.y == 10) //"transform" gives you acces to the transform component
{ //of the object the script is attached to
Debug.Log("MILK GANG");
}
//For the object position relative to its Parent Object
if(transform.localPosition.y == 10)
{
Debug.Log("MILK GANG");
}
If you want to change the value of the position of your object then
transform.position = new Vector2(6, 9)//Nice
//BTW new Vector2 can be used if you dont
//want to assign a completely new variable
However, if you want to get a reference (Basically a variable that tells the code your talking about this component) to it.
private Transform Trans;
void Awake() //Awake is called/being executed before the first frame so its
{ //better than void Start in this case
Trans = GetComponent<Transform>();
Trans.position = new Vector2(69, 420); //Nice
}
This is the code way of doing it but there's another way that uses Unity
[SerializeField] private Transform Trans;
//[SerializeField] makes the variable changeable in Unity even if it is private so you
//can just drag and drop on to this and you good to go
Hope this help
if it doesn't
then welp I tried lel
You can use a script added to gameobject to check transform.position of the object.
if(transform.position.y < ylvl)
{
//do something
}
where ylvl is the integer of the height you want to check
Hi I am making a Generation Game In unity, and I have custom meshes and I wanted a function to convert Mesh to MeshFilters in the fastest way cause this function will get a input of a Array of Meshes and the output will be a Array of MeshFilters.
Thanks :)
This should be pretty streight forward.
In general you don't simply "create" MeshFilters. You rather attach them to a GameObject. There are bascially three ways to do so:
use AddComponent in order to attach it to an existing object
use Instantiate in order to create a clone instance of an existing prefab
use the constructor of GameObject and pass the according type(s) in as parameters
And well then just assign your Mesh to MeshFilter.sharedMesh or MeshFilter.mesh in this case where you assign the entire mesh it shouldn't really make a difference.
So you could e.g. simply do
// Needed for option B - see below
//[SerializeField] private MeshFilter preparedPrefab;
public MeshFilter[] CreateObjects(Mesh[] meshes)
{
var amount = meshes.Length;
var meshFilters = new MeshFilter[amount];
for(var i = 0; i < amount; i++)
{
// here you have multiple options
// A - create a new empty GameObjects with the MeshFilter component
meshFilters[i] = new GameObject("someName" /*, typeof(MeshRenderer), etc*/).AddComponent<MeshFilter>();
// B - Rather already prepare a prefab/template which contains all the components you need
// in particular you might also want a MeshRenderer in roder to see your objects
// and e.g. MeshCollider in order to apply physics and raycasting to your objects
//meshFilter[i] = Instantiate(prapredPrefab);
meshFilter[i].sharedMesh = meshes[i];
}
return meshFilters;
}
Note that a Mesh itself has no information about any position, rotation, scale and child-parent relationships in your scene. For this you would need more information.
I tried to get Terrains from Resources.FindObjectsOfTypeAll(typeof(Terrain)), and then activate it depend on the situations.
But it return Objects.
I had tried to cast it to GameObject by (GameObect)obj and obj as GameObject.
The first one raised an Invalid cast error, and the second returned a null.
The examples I was able to find online talked about Resources.Load mostly, which requires Instantiation.
But I don't think FindObjectsOfTypeAll requires instantiation, because the GameObjects are "already there"! Right!?
So could somebody please be so kind and teach me how can I cast Objects into GameObject so I could activated it!?
Much appreciated!
Terrain is a component, so its associated GameObject is accessed via the gameObject property.
Something like:
var go = ((Terrain)obj).gameObject;
Hi think you could use something like finding the terrain with the name of the object or the name of the tag, maybe this could help:
public class ExampleClass : MonoBehaviour
{
public GameObject terrain;
public GameObject[] terrains;
void Example()
{
// This returns the GameObject named Hand.
terrain = GameObject.Find("Hand");
// returns a list of the game objects with tags = 'terrain'
terrains = GameObject.FindGameObjectsWithTag("terrain");
//returns a single object with the tag terrain
terrain = GameObject.FindWithTag("terrain");
}
}
I'm trying to make a Pinata GameObject, that when clicked bursts and gives a variable number of Gift GameObjects with various images and behaviors in them.
I'm also not sure what the unity vocabulary for this is so as to look this up in unity docs.
Can anyone please lend me a hand here? Thanks!
There are several ways to handle this.
The simple way is to use Object.Instantiate, Object Instantiation is the vocab you're after.
This will create a copy of a predefined Unity object, this can be a gameobject or any other object derived from UnityEngine.Object, check the docs for more info https://docs.unity3d.com/ScriptReference/Object.Instantiate.html.
In your case, your Pinata would have an array, or list, of prefabs. These prefabs are created by you with a certain behaviour and sprite for each one. When the Pinata bursts, you instantiate random prefabs at random positions surrounding the Pinata, up to you how to position these objects.
Something along these lines should do the trick:
class Pinata : Monobehaviour
{
public GameObject[] pickupPrefabs;
public int numberOfItemsToSpawn; //This can be random
//any other variables that influence spawning
//Other methods
public void Burst()
{
for(int i = 0; i < numberOfItemsToSpawn; i++)
{
//Length - 1 because the range is inclusive, may return
//the length of the array otherwise, and throw exceptions
int randomItem = Random.Range(0, pickupPrefabs.Length - 1);
GameObject pickup = (GameObject)Instantiate(pickupPrefabs[randomItem]);
pickup.transform.position = transform.position;
//the position can be randomised, you can also do other cool effects like apply an explosive force or something
}
}
}
Bare in mind, if you want the game to be consistent, then each behaviour prefab would have there own predefined sprite, this would not be randomised. The only thing randomised would be the spawning and positioning.
If you did want to randomise the sprites for the behaviours then you'd have to add this to the Pinata class:
public class Pinata : Monobehaviour
{
//An array of all possible sprites
public Sprite[] objectSprites;
public void Burst()
{
//the stuff I mentioned earlier
int randomSprite = Random.Range(0, objectSprites.Length - 1);
SpriteRenderer renderer = pickup.GetComponent<SpriteRenderer>();
//Set the sprite of the renderer to a random one
renderer.sprite = objectSprites[randomSprite];
float flip = Random.value;
//not essential, but can make it more random
if(flip > 0.5)
{
renderer.flipX = true;
}
}
}
You can use Unity random for all your random needs, https://docs.unity3d.com/ScriptReference/Random.html
Hopefully this'll lead you in the right direction.