- Home /
Why can't I use Selection.GetFiltered with GameObjects?
When I look this method up it only says to use a type, but the GameObject type does not work with it. How should I write this instead so unity does not give me the error ('GameObject' is a type, which is not valid in the given context)?
private void Update()
{
foreach(GameObject g in Selection.GetFiltered(GameObject, SelectionMode.TopLevel | SelectionMode.OnlyUserModifiable | (g.tag == "Tile")))
{
}
}
Answer by jdean300 · Feb 14, 2017 at 01:36 AM
GameObject is a type, but not a Type object. This method needs a Type object. You need to use typeof(GameObject)
which creates the Type object.
private void Update()
{
foreach(GameObject g in Selection.GetFiltered(typeof(GameObject), SelectionMode.TopLevel | SelectionMode.OnlyUserModifiable | (g.tag == "Tile")))
{
}
}
EDIT: Check comment for error. (g.tag == "Tile") will not work as shown here
Thank you for that, but now, with the script that follows, I am getting the error (The name 'g' does not exist in current context.) with the g.tag part.
using UnityEngine;
using UnityEditor;
using System.Collections;
[ExecuteInEdit$$anonymous$$ode]
public class Snap : $$anonymous$$onoBehaviour {
private void Update()
{
foreach(GameObject g in Selection.GetFiltered(typeof(GameObject), Selection$$anonymous$$ode.TopLevel | Selection$$anonymous$$ode.OnlyUser$$anonymous$$odifiable | (g.tag == "Tile")))
{
SpriteRenderer spr = g.GetComponent<SpriteRenderer>();
Transform t = g.transform;
g.transform.position = new Vector3(
(t.position.x - (t.position.x % 1)) + spr.bounds.extents.x,
(t.position.y - (t.position.y % 1)) + spr.bounds.extents.y,
(t.position.z - (t.position.z % 1)) + spr.bounds.extents.z
);
}
}
}
You can't use g in the line g.tag == "Tile"
because it is not defined until you are inside the foreach loop. Add this inside your loop:
if (g.tag != "Tile")
continue;
Alright It worked and I used this.
using UnityEngine;
using UnityEditor;
using System.Collections;
[ExecuteInEdit$$anonymous$$ode]
public class Snap : $$anonymous$$onoBehaviour {
private void Update()
{
//This finds all gameObjects I can move
foreach(GameObject g in Selection.GetFiltered(typeof(GameObject), Selection$$anonymous$$ode.TopLevel | Selection$$anonymous$$ode.OnlyUser$$anonymous$$odifiable ))
{
if (g.tag == "Tile")
{
//These splits the GameObject into a Transform and SpriteRenderer
SpriteRenderer spr = g.GetComponent<SpriteRenderer>();
Transform t = g.transform;
//This changes the objects transform to align to the grid in unity
g.transform.position = new Vector3(
(t.position.x - (t.position.x % 1)) + spr.bounds.extents.x,
(t.position.y - (t.position.y % 1)) + spr.bounds.extents.y,
(t.position.z - (t.position.z % 1)) + spr.bounds.extents.z
);
}
}
}