Search Unity

Unity UI Problem to position similar Image at the same place C#

Discussion in 'UGUI & TextMesh Pro' started by pKallv, Sep 9, 2018.

  1. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    I do not understand what i am doing wrong here. I am trying the following:

    1) Positioned 4 x Images (Cards) on UI scene
    Code (CSharp):
    1. public Image aceHeartZone, aceClubZone, aceDiamondZone, aceSpadeZone;
    2) The ace-cards are in the same hierarchy, in the Editor, as the normal cards:

    Skärmavbild 2018-09-09 kl. 18.35.24.png

    3) I copy the positions from the AceXX cards to Vector2 properties

    Code (CSharp):
    1. zone10 = aceHeartPos.rectTransform.localPosition;
    2. zone20 = aceClubPos.rectTransform.localPosition;
    3. zone30 = aceDiamondPos.rectTransform.localPosition;
    4. zone40 = aceSpadePos.rectTransform.localPosition;
    4) On the cards i have the following snippet:
    Code (CSharp):
    1.  _x = _prep.zone10.x;
    2.  _y = _prep.zone10.y;
    3.  myRectTransform.anchoredPosition = new Vector2(_x, _y);
    5) And the card is not positioned correctly:

    Skärmavbild 2018-09-09 kl. 18.29.56.png

    Behind the actual cards-images is the ace card-images, which is from where i pick the positions

    QUESTION:
    What do I do wrong here?
     
  2. Johannski

    Johannski

    Joined:
    Jan 25, 2014
    Posts:
    826
    Did you try setting the localposition instead of anchoredposition? (Since you're storing the localposition).
    Code (CSharp):
    1.  myRectTransform.localPosition= _prep.zone10;
     
  3. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    or the other way around: did you try to retrieve the anchored position instead of the local one?
    Code (CSharp):
    1.     zone10 = aceHeartPos.rectTransform.anchoredPosition;
    2.     zone20 = aceClubPos.rectTransform.anchoredPosition;
    3.     zone30 = aceDiamondPos.rectTransform.anchoredPosition;
    4.     zone40 = aceSpadePos.rectTransform.anchoredPosition;
    5.  
    you should also make sure that the anchors and pivots of all the elements are the same.

    another option: set the anchor min / max to the same as of the other object. That's how I usually do it.
     
  4. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    Friends, first i would really want to thank you all for the help. Secondly, i feel really stupid when I realize what mistake i done. Like a few said i mixed the localPosition and the anchoredPosition and that created the mess. Really STUPID mistake that I should have been able to figure out myself :-( ...I guess i got blind looking at the code all the time.

    I have now changed all, except the drag, to anchoredPosition and it works as expected.

    Again a BIG thank you.

    ps. At least I learned something :)
     
    Hosnkobf likes this.