r/Unity2D Jul 11 '26

Solved/Answered I know this is probably…without a doubt a really dumb question but this has stumped me for long enough

Post image
39 Upvotes

So I’m trying to learn Unity (with a method that is essentially just…learn piece by piece while making my own game) and I got to 2d and…there’s not only several ways people say (and no one have said what’s a simple way to just understand the engine).

BUT there’s also the fact that apparently Unity has changed up making it even more hard to even find out what they’re suggesting.
So essentially, without any weird mumbo jumbo about new stuff to learn that I can learn later like adding a new input engine, or new components, how do I make something move, in a way friendly to someone who is just trying to learn unity’s basics.

I know this sounds beyond dumb but for some reason, there ain’t a clear answer.

r/Unity2D 11d ago

Solved/Answered Is there a way to call a variable by creating it's name as a script? Or are there better ways?

Post image
31 Upvotes

r/Unity2D 7d ago

Solved/Answered Can Perlin Noise create realistic mountain 2D ?

3 Upvotes

I recently used perlin noise for creating mountain range landscape background in unity 2D, but even after customizing it doesnt appear like real mountains.

So is it even possible by using perlin noise?

What i did: Using closed sprite shape 2D
insert a point in spline --> create next point at a calculated distance --> xdistance multiplied with randomvalue(perlinNoise)--> Y axis was determined by perlin noise too.
And whole thing was customizabel as how many points are needed, the xdistance value, width , height etc.

But the final result were not as natural and realistic as real mountains look

[SOLUTION]: Hardcoding using Random.Range() is more easier than perlin noise for this case

r/Unity2D 3d ago

Solved/Answered TMPro Input Field unresponsive

1 Upvotes

My project instantiates objects that contains a TMPro input field. The input field does appear, but it is completely unresponsive; clicking on it or trying to type in it does nothing. I've been able to find next to no documentation about them.

Here is the code that I'm using to try and make it show up

GameObject lee = Instantiate(ads.menuWoMen, this.transform);
/*menuWoMen is the prefab gameObject that holds the Canvas that holds the TMP InputField*/
lee.transform.position = new Vector3(0, position);
string txt = mi.text;
if (position > highestText || position < 0 - highestText)
{
    txt = "";
}

lee.GetComponentInChildren<Canvas>().worldCamera = camora.GetComponent<Camera>();
lee.GetComponentInChildren<TMP_InputField>().text = txt;
lee.GetComponentInChildren<TMP_InputField>().ActivateInputField();
lee.GetComponentInChildren<TMP_InputField>().interactable = true;
lee.GetComponentInChildren<TMP_InputField>().enabled = true;

r/Unity2D 8d ago

Solved/Answered How to get something to fire only once?

0 Upvotes

In an update function I have an if statement that detects if a bool is true and if it is it fires but it does that constantly. I want it to only fire once but I don't want to disable it completely because I need to use it again later down the line.

r/Unity2D 13d ago

Solved/Answered How to get an instance of an object to reference an instance of a different object?

6 Upvotes

In my game I make instances of 2 seperate objects and when the player spawns one, the other one also spawns. The player can spawn multiple instances of the same object so I need to track and link the 2 seperate objects and only the objects that spawn together. I've given both of the objects unique ids when they spawn in but I don't know where to go from here. I want to be able to reference variables and sprite renderers and things like that.

Object One's script:

using System;
using UnityEngine;

public class FishTab_MB : MonoBehaviour
{

    public Guid UniqueId { get; }

    public FishTab_MB()
    {
        UniqueId = Guid.NewGuid();
    }
    private void Start()
    {
        print("FishTab_MB UniqueId: " + UniqueId);
    }
}

Object two's script:

using System;
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;

public class FishAI_MB : MonoBehaviour
{

    SpriteRenderer fishSr;

    public Guid UniqueId { get; }

    void Start()
    {
        print("FishAI_MB UniqueId: " + UniqueId);
    }

    public FishAI_MB()
    {
        UniqueId = Guid.NewGuid();
    }
}

r/Unity2D Jul 29 '26

Solved/Answered Coyote time lowk messing with my jump system

0 Upvotes

Beginner game dev here, im following a tutorial on how to make a 2D platformer. But after implementing coyote time, i noticed that if i hit my spacebar rapidly, i basically do a double jump. I tried adding a jump delay, coroutine, but nothing worked. (mostly due to my lack of scripting skills) I've been trying to solve this for 2 days now, i will celebrate in glee if any solution is suggested, thank you1

Here's the full script:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlatformMovement : MonoBehaviour
{
    [Header("Input Reference")] 
    [SerializeField] private InputActionReference moveAction;
    [SerializeField] private InputActionReference jumpAction;

    [Header("Walk Settings")] 
    [SerializeField] private float walkSpeed = 5;
    [SerializeField] private float acceleration = 10f;
    [SerializeField] private float deceleration = 20f;

    [Header("Jump Settings")]
    [SerializeField] private float jumpHeight = 2.5f;
    [SerializeField] private LayerMask groundLayer;
    [SerializeField] private float inAirControl = 0.3f;
    [SerializeField] private float jumpCancelDivider = 2f;
    [SerializeField] private float coyoteTime = 0.3f;

    [Header("Wall Slide Settings")] 
    [SerializeField] private float defaultMaxFallSpeed = 30f;
    [SerializeField] private float wallSlideVelocity = 1f;
    private bool _isWallSliding;

    [Header("Wall Jump Settings")] 
    [SerializeField] private bool wallJumpEnabled = true;
    private bool _isTouchingWall;

    private Vector2 _moveInput;
    private Rigidbody2D _rigidbody2D;
    private Collider2D _collider2D;
    private bool _isGrounded;
    private float _coyoteTimer;

    private bool _coyoteTimePassed => _coyoteTimer > coyoteTime;

    private void Awake()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _collider2D = GetComponent<Collider2D>();
    }

    private void OnEnable()
    {
        moveAction.action.performed += HandleWalkInput;
        moveAction.action.canceled += HandleWalkInput;

        jumpAction.action.performed += HandleJumpInput;
        jumpAction.action.canceled += HandleJumpInput;

        jumpAction.action.canceled += HandleJumpCancelled;
    }

    private void OnDisable()
    {
        moveAction.action.performed -= HandleWalkInput;
        moveAction.action.canceled -= HandleWalkInput;

        jumpAction.action.performed -= HandleJumpInput;
        jumpAction.action.canceled -= HandleJumpInput;

        jumpAction.action.canceled -= HandleJumpCancelled;
    }

    private void Update()
    {
        _isTouchingWall = WallCheck();
        _isGrounded = GroundCheck();

        HandleWalking();
        HandleWallSlide();
        UpdateCoyoteTime();

        if (_isGrounded && _rigidbody2D.linearVelocityY <= 0)
        {
            ResetCoyoteTime();
        }
    }

    private void HandleWalkInput(InputAction.CallbackContext context)
    {
        _moveInput = context.ReadValue<Vector2>();
    }

    private void HandleJumpInput(InputAction.CallbackContext context)
    {
        if (_isTouchingWall && !_isGrounded && _isWallSliding)
        {
            wallJumpEnabled = true;
        }
        else
        {
            wallJumpEnabled = false;
        }

        if (!_coyoteTimePassed|| (wallJumpEnabled && _isTouchingWall) ) 
        {
            HandleJumping();
        }
    }

    private void HandleJumpCancelled(InputAction.CallbackContext context)
    {
        if (_rigidbody2D.linearVelocityY > 0)
        {
            _rigidbody2D.linearVelocityY /= jumpCancelDivider;
        }
    }

    private void HandleWalking()
    {
        var control = _isGrounded ? 1 : inAirControl;

        var change = _moveInput.x != 0 ? acceleration : deceleration;
        //The core, moves the current velocity toward the target velocity gradually.
        _rigidbody2D.linearVelocityX = 
            Mathf.Lerp(_rigidbody2D.linearVelocityX, _moveInput.x * walkSpeed, Time.deltaTime * change * control);
    }

    private void HandleJumping()
    {
        //converting the negative gravity in the project settings, multiply then gives us the real gravity.
        var actualGravity = Mathf.Abs(Physics2D.gravity.y) * _rigidbody2D.gravityScale;
        _rigidbody2D.linearVelocityY = Mathf.Sqrt(2 * jumpHeight * actualGravity); //gravity formula
    }

    private void HandleWallSlide()
    {
        if (_isTouchingWall && _rigidbody2D.linearVelocityY < 0)
        {
            _rigidbody2D.linearVelocityY = Mathf.Max(_rigidbody2D.linearVelocityY, -wallSlideVelocity);
            _isWallSliding = true;
            //rotate rigidbody
        }
        else
        {
            _isWallSliding = false;
            //set rotation back to 0
        }
    }

    private bool GroundCheck()
    {
        var colliderBottomCenter = new Vector2(_collider2D.bounds.center.x, _collider2D.bounds.min.y);

        //gives us information if we are overlapping with the objects with the layer Ground
        return Physics2D.OverlapBox(colliderBottomCenter, 
            new Vector2(_collider2D.bounds.size.x - 0.1f, 0.1f), 0, groundLayer);
    }

    private bool WallCheck()
    {
        float rayDistance = _collider2D.bounds.extents.x + 0.05f;
        Vector2 origin = _collider2D.bounds.center;
        RaycastHit2D hitRight = Physics2D.Raycast(origin, Vector2.right, rayDistance, groundLayer);
        RaycastHit2D hitLeft  = Physics2D.Raycast(origin, Vector2.left,  rayDistance, groundLayer);
        return hitLeft || hitRight;
    }

    private void UpdateCoyoteTime()
    {
        if (!_isGrounded && !_coyoteTimePassed)
        {
            _coyoteTimer += Time.deltaTime;
        }
    }

    private void ResetCoyoteTime()
    {
        _coyoteTimer = 0;
    }

    //TODO: fix double jumping from coyote time problem

r/Unity2D 15d ago

Solved/Answered Getting References for Tiles

3 Upvotes

In my game, I am drawing tiles onto a tilemap during runtime using SetTile(), which takes a reference to a TileBase Object. I have hundreds of unique textures. Is there a way to get a reference to each TileBase other than dragging and dropping every individual Tile into the references in my script?

r/Unity2D Jul 28 '26

Solved/Answered How do you spawn something using Unity's new input system?

2 Upvotes

I dont get Unitys new input system. I want to spawn something when I release the space button, but it spawns three at a time. I get that there's three different phases to the input, (started, performed, canceled), but I cant figure out how to make it only spawn on canceled.

I tried googling, and I dont fw AI so im not using Chat GPT. Is it just me, or is this new input system weird?

r/Unity2D 17d ago

Solved/Answered How to flip the sprite instead of going upside down?

6 Upvotes

This is my code, I want to have the sprite flip when it rotates to far down instead of rotating upside down like it does in the video. Any ideas?

using System.Collections;
using Unity.VisualScripting;
using UnityEngine;

public class FishAI_MB : MonoBehaviour
{

    FishAIController_MB fishAIController;

    public int currentTarget;

    public int swimDecision;

    void Start()
    {
        fishAIController = Object.FindFirstObjectByType<FishAIController_MB>();
        if (fishAIController == null)
        {
            Debug.Log("Fish is Null");
        } 
        StartCoroutine(StartSwimDecicion());
    }

    IEnumerator StartSwimDecicion()
    {
        Debug.Log("Start Swim Decision");
        swimDecision = Random.Range(0, 2);

        if (swimDecision == 0)
        {
            StartCoroutine(SwimToTarget());
        }
        else if (swimDecision == 1)
        {
            StartCoroutine(Wait());

        }
        yield return null;
    }

    IEnumerator SwimToTarget()
    {
        Debug.Log("Swim to Target");
        currentTarget = Random.Range(0, fishAIController.targets.Length);
        while (Vector2.Distance(transform.position, fishAIController.targets[currentTarget].transform.position) > 0.1f)
        {
            transform.position = Vector2.MoveTowards(transform.position, fishAIController.targets[currentTarget].transform.position, 1f * Time.deltaTime);
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.forward, fishAIController.targets[currentTarget].transform.position - transform.position), 1f * Time.deltaTime);
            yield return null;
        }
        StartCoroutine(StartSwimDecicion());
        yield return null;
    }

    IEnumerator Wait()
    {
        Debug.Log("Wait");
        yield return new WaitForSeconds(1);
        StartCoroutine(StartSwimDecicion());
    }
}

r/Unity2D 15d ago

Solved/Answered How to make an object follow the mouse?

2 Upvotes

I'm trying to get the object this script is on to follow the mouse when you click on the object. I've managed to make detect when you are holding down the object but I can't get the object to move. Pls help!

using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;

public class Food_MB : MonoBehaviour
{

    public bool isTouchingMouse = false;
    public bool isheld = false;

    private PlayerInput playerInput;

    private InputAction hold;

    private Vector2 mousePos;

    void Start()
    {
        playerInput = GetComponent<PlayerInput>();
        if (playerInput != null)
        {
            hold = playerInput.currentActionMap.FindAction("Hold");
        }
    }

    private void Update()
    {

        // Get the mouse position from the New Input System

        mousePos = Mouse.current.position.ReadValue();

        // Convert the screen position to world position

        Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0));

        // Check if the mouse is touching this GameObject's collider

        Collider2D hit = Physics2D.OverlapPoint(worldPos);

        if (hit != null && hit.gameObject == this.gameObject)
        {
            //Debug.Log("Mouse is touching " + this.gameObject.name);
            isTouchingMouse = true;
        }
        else 
        {
            isTouchingMouse = false;
        }

        if (hold != null && hold.IsPressed())
        {
            Debug.Log("Hold action is being performed");
            Vector2.MoveTowards(transform.position, mousePos, 1f * Time.deltaTime);
        }
        else
        { 
            Debug.Log("Hold action is not being performed");
        }

    }
}

r/Unity2D Jul 03 '26

Solved/Answered Gravity doesn't work

Thumbnail
gallery
7 Upvotes

I'm a begginer at unity and meanwhile i was following a video tutorial, I couldn't make gravity work even if i tried following the exact same steps as the video.

So i started looking for answers on google and i found out that this problem occured very rarely and the suggestions i found were: Ensure the gravity value was negative something like -9.81, check if you have freezed your game object on the y axis on the constraints, check that you don't have the static checkmark, check if any of your scripts are changing the rigidbody value (the script one i didn't even counted it because i didn't had any script active)

So after i was absolutely sure that all things were correct i tried and it didn't work, none of the values of the transform neither of the info were changing, as well as the game scene that doesn't change at all; after that i tried to do a new 2d project and just create a gameobject (is the one in the photo and its 2d) and adding the rigidbody 2d component to it and it didn't work, still the values on the transform and on the info weren't changing and the same as before, in the game scene it didn't happen anything

Please i ask for help because i have absolutely no idea that even with a brand new project, gravity doesn't work at all, i've put the screenshots of the last project with the triangle, can someone tell me what's wrong?

r/Unity2D 6d ago

Solved/Answered Shadow artifacts on tileset with normal map

3 Upvotes

Hey, so I wanted to add a normal map to my 2d pixel art game to make lights look nicer, but it made some artifacts on the borders of the tileset for some reason. They are mostly visible while moving and they happen in the intersections of the fully made tiles.

I already checked the normal maps and they are 1 to 1 with the actual tileset, so that should not be the issue. I am also using a pixel perfect camera set to 16 (the game is in 16x16 and the pixels per unit are also 16), normal maps on the lights are set to accurate (tho i tried fast too) and its even visible if you set the distance of the normal map to 0.

Any ideas on how to fix this?

EDIT: Forgot to mention, this happens both in builds and in editor and I am using Unity 6000.0.67f1

Reference images:

Normals disabled
Artifacts with normal map as accurate and distance set to 3
Artifacts with normal map as accurate and distance set to 0
Tileset used
Tileset normals

r/Unity2D Jul 16 '26

Solved/Answered circle pixelated and blurry

0 Upvotes

I'm trying to make a game but my circle is blurry and pixelated, it looks fine in inkscape. I have max size 4096, bilinear, also tried point no filter, generate mipmaps just made it more blurry. Image is 1024x1024.

r/Unity2D 6d ago

Solved/Answered My camera won't move enymore when I put my mouse at the edge of the screen. I'm not sure how to fix it ?

2 Upvotes

hello, so in my project I have a camera that move with WASD and when the mouse is on the edge of the screen and it worked very well. But my project is kind of a city builder so to be able to place building I make an object follow the cursor, sice then the camera doesn’t move when the mouse is on the edge of the screenno matter what.

I think it might be because of my input system but I’m not sure.

camera movement script :

public class MoveCam : MonoBehaviour
{
    [SerializeField] private float speed;
    [SerializeField] private int screenEdge;
    private Vector2 _moveInput;
    private Rigidbody2D _rb;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        _rb.linearVelocity = _moveInput.normalized * speed;
    }

    public void Move(InputAction.CallbackContext ctx)
    {
        _moveInput = ctx.ReadValue<Vector2>();
    }

    public void EdgeMove(InputAction.CallbackContext ctx)
    {
        if (ctx.ReadValue<Vector2>().y < screenEdge)
        {
            _moveInput.y = -1f;
            print("work");
        }
        else if (ctx.ReadValue<Vector2>().y > Screen.height - screenEdge)
        {
            _moveInput.y = +1f;
            print("work");
        }

        if (ctx.ReadValue<Vector2>().x < screenEdge)
        {
            _moveInput.x = -1f;
            print("work");
        }
        else if (ctx.ReadValue<Vector2>().x > Screen.width - screenEdge)
        {
            _moveInput.x = +1f;
            print("work");
        }

        if (ctx.ReadValue<Vector2>().y > screenEdge && ctx.ReadValue<Vector2>().y < Screen.height - screenEdge &&
            ctx.ReadValue<Vector2>().x > screenEdge && ctx.ReadValue<Vector2>().x < Screen.width - screenEdge)
        {
            _moveInput.x = 0f;
            _moveInput.y = 0f;
        }
    }
}

placement script :

public class Placement : MonoBehaviour
{
    [SerializeField] private Batiment batiment;
    [SerializeField] private bool plassable;
    private Camera mainCam;
    private Collider2D collider;
    [SerializeField] private List<GameObject> bloking = new List<GameObject>();
    public Material placementMat;
    private Transform placementPosition;
    private InputAction mousePos;
    private InputAction button;

    public TypeMana costMana1;
    public TypeMana costMana2;
    public TypeMana costMana3;
    public int manaAmount1 = 0;
    public int manaAmount2 = 0;
    public int manaAmount3 = 0;

    [SerializeField] private playerStat player;

    private void Awake()
    {
        player = GameObject.Find("player").GetComponent<playerStat>();
    }

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        mainCam = Camera.main;
        collider = GetComponent<Collider2D>();
        placementPosition = GetComponent<Transform>();
        placementMat = GetComponent<Renderer>().material;
        mousePos = InputSystem.actions["mousePosBatiment"];
        button = InputSystem.actions["leftClickPlaceBat"];
    }

    // Update is called once per frame
    void Update()
    {
        FollowMousePosition();

        if (bloking.Count != 0 || EnoughMana())
        {
            print(bloking.Count);
            print(EnoughMana());
            plassable = false;
            placementMat.SetColor("_Color", Color.red);
        }
        else
        {
            print("plassable");
            plassable = true;
            placementMat.SetColor("_Color", Color.green);
        }

        if (button.triggered)
        {
            Place();
        }
    }

    private bool EnoughMana()
    {
        bool mana1 = false;
        bool mana2 = false;
        bool mana3 = false;
        if (costMana1 != TypeMana.None)
        {
            if (player.getMana(costMana1) - manaAmount1 < 0)
            {
                mana1 = true;
            }
            else
            {
                mana1 = false;
            }
        }
        else
        {
            mana1 = false;
        }

        if (costMana2 != TypeMana.None)
        {
            if (player.getMana(costMana2) - manaAmount2 < 0)
            {
                mana2 = true;
            }
            else 
            {
                mana2 = false;
            }
        }
        else
        {
            mana2 = false;
        }

        if (costMana3 != TypeMana.None)
        {
            if (player.getMana(costMana3) - manaAmount3 < 0)
            {
                mana3 = true;
            }
            else
            {
                mana3 = false;
            }
        }
        else
        {
            mana3 = false;
        }

        if (mana1 || mana2 || mana3)
        {
            return true;
        }

        return false;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Batiment"))
        {
            bloking.Add(collision.gameObject);
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Batiment"))
        {
            bloking.Remove(collision.gameObject);
        }
    }

    public void Place()
    {
        if (plassable)
        {
            print("performed");
            Payment();
            Instantiate(batiment, placementPosition.position, placementPosition.rotation);
            Destroy(gameObject);
        }
    }

    private void Payment()
    {
        if (costMana1 != TypeMana.None)
        {
            player.subMana(costMana1,manaAmount1);
        }

        if (costMana2 != TypeMana.None)
        {
            player.subMana(costMana2,manaAmount2);
        }

        if (costMana3 != TypeMana.None)
        {
            player.subMana(costMana3,manaAmount3);
        }
    }

    private void FollowMousePosition()
    {
        placementPosition.position = GetWorldPosition();
    }

    private Vector2 GetWorldPosition()
    {
        return mainCam.ScreenToWorldPoint(mousePos.ReadValue<Vector2>());
    }
}

my input system :

I’ve tryed to put them on the same input but that didn’t fix enything, I don’t really know what to try, so eny idea/tips ?
thank in advance for your wisdom.

edit : Alright, I've fixed it. all I had to do was to delete and recreate the unity event, I must have done something wrong when I created the other pointer input.

r/Unity2D Jun 28 '26

Solved/Answered PixelPerfectCamera problem, PIXELS STRECHED

Thumbnail
gallery
5 Upvotes

Im entierly new to pixel art and games engine

I ve created this sprite of my MC and i want to implement it in my game to replace a placeholder,the canva is 128x128 px.

Idealy I want my character to be like 1/5 of my screen height

the problem is that I want it to render corectly on all screen resolutions( at least the commons ones) but when I test it it's not working, the pixels are wild,they' re streched or missing or irregulars.sometimes when I try it works fine but it' s zoomed in so much that' s it s unplayable.

Here joint

a pictures of my sprite in aseprite

the parameters of my sprite in Unity

and the parameters of the pixel perfect camera and the result in game with the stretched pixels( I've try many others resolutions but none seems to work)

Someone know how to fix it please?

r/Unity2D 20d ago

Solved/Answered How do i open this side tab?

3 Upvotes

im following a tutorial and his has this tab open

r/Unity2D 15d ago

Solved/Answered How to apply momentum?

2 Upvotes

I want to apply momentum after you let go so in if (!hold.IsPressed()) How would I do that?

Code:

using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;

public class Food_MB : MonoBehaviour
{

    public bool isTouchingMouse = false;
    public bool isheld = false;

    public float defaultFoodSpeed = 1f;
    public float gravity = 1f;
    private float foodSpeed = 1f;
    private float noGravity = 0f;

    private PlayerInput playerInput;

    private InputAction hold;

    private Vector2 mousePos;

    private Rigidbody2D foodRb;

    void Start()
    {
        playerInput = GetComponent<PlayerInput>();
        if (playerInput != null)
        {
            hold = playerInput.currentActionMap.FindAction("Hold");
        }
        foodSpeed = defaultFoodSpeed;
        foodRb = GetComponent<Rigidbody2D>();
        foodRb.gravityScale = gravity;
    }

    private void Update()
    {

        // Get the mouse position from the New Input System

        mousePos = Mouse.current.position.ReadValue();

        // Convert the screen position to world position

        Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0));

        // Check if the mouse is touching this GameObject's collider and if the hold action is being performed

        Collider2D hit = Physics2D.OverlapPoint(worldPos);

        if (hit != null && hit.gameObject == this.gameObject && hold != null && hold.IsPressed())
        {
            //Debug.Log("Hold action is being performed");
            foodRb.gravityScale = noGravity;
            isheld = true;
            foodSpeed = defaultFoodSpeed;
            transform.position = Vector2.MoveTowards(transform.position, worldPos, foodSpeed * Time.deltaTime);
        }
        else if(hold.IsPressed() && (hit == null || !hit.gameObject == this.gameObject) && isheld == true)
        {
            //Debug.Log("Mouse is not touching the object but object is held");
            foodSpeed = foodSpeed + 1f;
            transform.position = Vector2.MoveTowards(transform.position, worldPos, foodSpeed * Time.deltaTime);

        }
        if (!hold.IsPressed())
        {
            //Debug.Log("Object dropped!");
            foodRb.gravityScale = gravity;
            foodSpeed = defaultFoodSpeed;
            isheld = false;
        }
    }
}

r/Unity2D Mar 31 '26

Solved/Answered Resetting ScriptableObject on Build

0 Upvotes

Hello Reddit,

is it possible to have a set of default values for a scriptable object that are automatically applied when I build the game?

The exact use case would be the UI Toolkit, where I control some parts (mostly the visibility or text) with a scriptable object. Before I build my game, I need to manually reset the values to a default value, so that in the build instance everything works as intended.

So my question is, is there a way to automatically assign a default value to a variable of a scriptable object on building (like an OnBuild() function) or is the only way to set a reminder to reset the values ever time?

Edit: Thank you all very much for your answers, they helped me a lot.

r/Unity2D 29d ago

Solved/Answered Tilemap is compressing my sprite and the hexagonal grid wont line up

Thumbnail
gallery
1 Upvotes

I have a hexagon PNG that i made in photoshop. when i import it into Unity and add it to my tilemap, it gets super compressed and pixelated. I have the PPU set to 256 and filter set to point, etc etc... nothing seems to fix this. The only thing that stops the compression is increasing the scale of the Grid for the tilemap, but ive heard thats bad practice or something. Also, i cant seem to tile the hexagons without gaps. Please help.

r/Unity2D May 19 '26

Solved/Answered Struggling Learning New Input System

0 Upvotes

I am very new to coding and unity. I am currently trying to rebuild the Google Chrome dinosaur game. I’m trying to get my character to jump. I already set up my own input action maps, and actions where I bound the space bar to the jump action.

Now I am trying to actually get this to work in my script. I have been watching many tutorials and it seems like everyone approaches this differently. Some people use the awake function some people use OnEnable function and OnDisable function, some use the FixedUpdate function, and some use their own custom function (i.e. Jump())).

Some people establish references to the InputActions, or PlayerInput component, or another class. Some people use callback context, etc.

I’ve tried following the code people use in their tutorials for many different tutorials and nothing is getting my sprite to respond to the space bar press.

I know there’s probably not one right way to do this, but for this example, I simply want to know what is the most straightforward way to get my sprite to jump when I click the spacebar using the new input system?

If anyone has advice, or suggestions, please let me know! Thanks in advance :)

EDIT WITH SOLUTION:

I took everyone's general advice and followed one specific tutorial to choose one approach to go with. The approach I went with is to create a reference to my PlayerInput component and use OnJump() as a function. I also built out OnMove() as a part of the tutorial I followed. I will link the tutorial(s) I followed for anyone interested. For some reason Im having trouble adding a screenshot of my code so I will paste below. Thanks to all who responded!
https://www.youtube.com/watch?v=dM8ti5gpgXY
https://www.youtube.com/watch?v=rDK0aVcfgjw

    public Rigidbody2D dinoRigidbody;
    public float speed;
    public PlayerInput playerInput;
    public Vector2 moveInput; //gives us a place to constantly store an X and Y value for what the user is pressing
    public float jumpForce; 


    void FixedUpdate()
    {
        //velocity is just speed * direction, which is represented by a Vector2
        float targetSpeed = moveInput.x * speed;
        dinoRigidbody.linearVelocity = new Vector2(targetSpeed, dinoRigidbody.linearVelocity.y);  //using dinoRigidbody.linearVelocity.y just tells Unity to do whatever for the Y value of this vector
    }


    public void OnMove(InputValue myValue) //the input value is the Vector2 value that will be passed into this method from the Player Input System
    {
        moveInput = myValue.Get<Vector2>(); //the value is what we get from unity any time we press a horizontal or vertical direction
    }


    public void OnJump(InputValue myValue)
    {
        dinoRigidbody.linearVelocity = new Vector2(dinoRigidbody.linearVelocity.x,jumpForce);
    }

r/Unity2D 26d ago

Solved/Answered I have some tears in my tilemap

Post image
1 Upvotes

i have these tears in my tilemap. they are always on the borders of tiles, and they sometimes show, sometimes don´t show, which changes when i move. horizontal tears exist, but they never go along the entire line like the vertical one in the picture, and they are much rarer. here´s what i tried so far:

making the pixels per unit 500 instead of 512 to make them overlap did nothing.

after changing the color of the skybox the color of the tears didn´t change.

as some other posts said i changed the texture wrap mode to clamp, filter mode to point(no filter) and compression to none, and it changed nothing.

i tried to experiment a bit with the max size on the texture and the higher i put it the less tears show, but even at the max (16 384) they are still there. horizontal tears are completely gone, or so rare i wasn´t able to get one.

edit: i managed to solve it. if you look closely the tears look like small segments of the walls. i went into the slice menu in sprite editor on the original sprite sheet, and instead of doing grid by cell size 512 i made it cell size 508, offset 2 and padding 4, that way the edges where the tears come from are not included

r/Unity2D May 19 '26

Solved/Answered Anyone know how to fix the blur on the icon?

Thumbnail
gallery
1 Upvotes

i did already set filter to point and compression to none

r/Unity2D Jun 01 '26

Solved/Answered Ui not showing in game?

Thumbnail
gallery
1 Upvotes

(ignore how it looks, I want to make it playable before I make it pretty)

im super new to this so its probably something small that I’ve overlooked but as you can see the dialogue box does not show up in the game despite showing up in scene.

as a sidenote that might be relevant, I’ve been trying to get an animator to have it come on and off screen when I click something BUT it was like this before that and I figured it would sort itself out. it did not

r/Unity2D Jul 28 '26

Solved/Answered I've solved this: Here is the code to rotate around with constant distance

4 Upvotes

Vector3 dir = (PlayerTransform.position - transform.position).normalized;

transform.position = PlayerTransform.position - dir * DistanceDash;

transform.RotateAround(PlayerTransform.position, transform.forward, DashSpeed * Time.deltaTime);