Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[Need Help] - Moving a Panel with C# - [Need Help]

Discussion in 'Scripting' started by LittleCatPaws, Feb 3, 2016.

  1. LittleCatPaws

    LittleCatPaws

    Joined:
    Feb 3, 2016
    Posts:
    2
    Hello :3

    I'm new to Unity and need help with something in a 2D game i'm trying to make.
    I want to make a panel's X position change after i click a button.

    it would be awesome if someone could give me a quick explanation on how to do this <3
    Thanks in advance
     
  2. Mich_9

    Mich_9

    Joined:
    Oct 22, 2014
    Posts:
    118
    Like opening and closing the panel? Or you need to move it freely around the screen?
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,848
    Make a script like this:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class MovePosition {
    4.     public Vector2 positionB;
    5.     Vector2 positionA;
    6.  
    7.     void Start() {
    8.         positionA = GetComponent<RectTransform>().anchoredPosition;
    9.     }
    10.  
    11.     public void MoveToPositionA() {
    12.         GetComponent<RectTransform>().anchoredPosition = positionA;
    13.     }
    14.  
    15.     public void MoveToPositionB() {
    16.         GetComponent<RectTransform>().anchoredPosition = positionB;
    17.     }
    18. }
    19.  
    Attach this to your panel, and assign positionB the position you want it to go to. Now, in your button's On Click event, invoke the MoveToPositionB method on your panel's MovePosition component.

    Cheers,
    - Joe
     
  4. Mich_9

    Mich_9

    Joined:
    Oct 22, 2014
    Posts:
    118
    Well, this literally moves the panel, but I think he may be asking how to animate it. Let's see what OP says.
     
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,848
    Could be. My mind-reading skills drop off sharply after 9PM.
     
    Mich_9 likes this.
  6. LittleCatPaws

    LittleCatPaws

    Joined:
    Feb 3, 2016
    Posts:
    2
    I created the script and attached the script to the panel and set the values.
    how do i invoke the MoveToPositionB method?
     
    Last edited: Feb 4, 2016
    JoeStrout likes this.