- Home /
The question is answered, right answer was accepted
Swapping UI image element positions
I have searched extensively for a solution to this problem and haven't been able to find one yet. I have the below script placed on an object I call the ability manager. My application is built in 2D.
private Controls controls;
public List<Canvas> abilityImageList = new List<Canvas>();
public Vector2[] currentPos = new Vector2[3];
public RectTransform current, up, down;
// Use this for initialization
void Start ()
{
controls = GameObject.Find("Settings").GetComponent<Controls>();
abilityImageList.Add(GameObject.Find("Ability1Sorting").GetComponent<Canvas>());
abilityImageList.Add(GameObject.Find("Ability2Sorting").GetComponent<Canvas>());
abilityImageList.Add(GameObject.Find("Ability3Sorting").GetComponent<Canvas>());
current = abilityImageList[0].GetComponentInChildren<RectTransform>();
down = abilityImageList[1].GetComponentInChildren<RectTransform>();
up = abilityImageList[2].GetComponentInChildren<RectTransform>();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKey(controls.up))
{
currentPos[0] = current.posi;
currentPos[1] = up.position;
currentPos[2] = down.position;
}
}
It finds the 3 canvas objects that I currently have, each with one image component (broken apart as such to allow changes to their order in layer). I'm hoping to make a sort of rotary ability selection menu. Currently, when I hit up (the key I have set to grab each images position) it returns the same X/Y value for each object. I've tried putting in localPosition and anchoredPosition with no luck. The returned values are always identical between the 3 objects.
Image for .position:
The result is similar regardless of which method I use. The values might change, but they are identical between the 3 images. I'd like to know if there's some different way I haven't found yet to get the positional information for the 3 images. Any help is greatly appreciated!
Answer by LCStark · Oct 11, 2018 at 07:25 PM
As the GetComponentInChildren
documentation states:
Returns the component of Type type in the GameObject or any of its children using depth first search.
So you're probably retrieving the RectTransform
of the Canvas
instead of the Image
. Try accessing the child first and then retrieving its component:
current = abilityImageList[0].transform.GetChild(0).GetComponent<RectTransform>();
or
current = abilityImageList[0].transform.Find("Ability1").GetComponent<RectTransform>();
You're totally right... I actually noticed that right before I came to check the page hoping nobody had seen it yet... Appreciate the quick response though!
Follow this Question
Related Questions
How to align pixel art with UI system ? 0 Answers
Pointer Enter event doesn't fire Unity 5.5 1 Answer
Force UIImage to stay on viewport? 0 Answers
Moving images around 0 Answers
Universal Method of finding pixel dimensions of UI elements 1 Answer