I need some Feedback on how to optimize my Code and inplement a Attack Parry System

I am new to Unity, C# or to OOP in general.

I am learning Unity right now, and all of the Scripts that I use are self made. Ai helped a little bit to like understand how to even write C# and so on. Before I started I read the entire W3Schools Documentation about C#, this helped alot to understand how OOP works. The Problem with AI (Github Copilot) is that it doesnt works all the time (has old Information) and W3School doesnt explains Unity. The Documentation from Unity itself, is very rough and I understand nothing. I look 90% up on Yt it helped but its always stuck with only one of the different solutions that are possible.

My Movement Script:

using System;
using UnityEngine;
using UnityEngine.InputSystem;

public class Movement : MonoBehaviour
{
    public LayerMask ground;
    public float jumpforce = 8f;
    public float accel = 8f;
    public float friction = 2f;
    public float maxSpeed;
    public float rotationSpeed = 1f;
    private bool isGroundTouched = false;
    private Rigidbody2D rb;
    private Collider2D col;
    Vector2 movementDirection = Vector2.zero;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        col = GetComponent<Collider2D>();
    }

    private void Update()
    {
        isGroundTouched = col.IsTouchingLayers(ground);

        if (Input.GetKeyDown(KeyCode.R))
        {
            rb.position = (new Vector2(0, 0));
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }

    private void FixedUpdate()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        movementDirection = new Vector2(horizontalInput, verticalInput).normalized;

        if (movementDirection != Vector2.zero)
        {
            float angle = Mathf.Atan2(movementDirection.y, movementDirection.x) * Mathf.Rad2Deg;
            rb.rotation = angle;
            
        }
        if (Input.GetKey(KeyCode.D))
        {
            horizontalInput = accel;

        }
        else if (Input.GetKey(KeyCode.A))
        {
            horizontalInput = -accel;
        }
        else
        {
            ApplyFriction();
        }

        if (!Mathf.Approximately(horizontalInput, 0f))
        {
            Move(horizontalInput);
        }

        LimitSpeed();
    }

    private void Move(float direction)
    {
        rb.AddForce(new Vector2(direction, 0));
    }

    private void ApplyFriction()
    {
        if (Mathf.Approximately(rb.linearVelocity.x, 0f))
        {
            rb.linearVelocity = new Vector2(0, rb.linearVelocity.y);
        }
        else
        {
            rb.linearVelocity = new Vector2(rb.linearVelocity.x * (1 - friction * Time.fixedDeltaTime), rb.linearVelocity.y);
        }
    }

    private void LimitSpeed()
    {
        if (rb.linearVelocity.x > maxSpeed)
        {
            rb.linearVelocity = new Vector2(maxSpeed, rb.linearVelocity.y);
        }
        else if (rb.linearVelocity.x < -maxSpeed)
        {
            rb.linearVelocity = new Vector2(-maxSpeed, rb.linearVelocity.y);
        }
    }

    private void Jump()
    {
        if (isGroundTouched)
        {
            rb.AddForce(new Vector2(rb.linearVelocity.x, jumpforce));
        }
    }
}

My Item Pickup:

using System;
using Unity.VisualScripting;
using UnityEngine;

public class ItemPickup : MonoBehaviour
{
    public GameObject[] items;
    public Transform grabpoint;
    public Transform raypoint;
    public float grabDistance;
    public LayerMask ItemLayer;
    private GameObject grabbedItem;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        
        RaycastHit2D hit = Physics2D.Raycast(raypoint.position, transform.right, grabDistance, ItemLayer);

        if (hit.collider != null)
        {
            if (Input.GetKeyDown(KeyCode.Q) && grabbedItem == null)
            {
                grabbedItem = hit.collider.gameObject;
                grabbedItem.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
                grabbedItem.transform.position = grabpoint.position;
                grabbedItem.transform.SetParent(transform);
            }
            else if (Input.GetKeyDown(KeyCode.Q))
            {
                grabbedItem.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
                grabbedItem.transform.SetParent(null);
                grabbedItem = null;
            }
        }
    }
}

My Camara Follow:

using UnityEngine;

public class CamaraFollow : MonoBehaviour
{

    public Transform target;
    public float yOffset = 1.5f;
    public float CamSpeed = 0.125f;

    // Update is called once per frame
    void Update()
    {
        Vector3 newpos = new Vector3(target.position.x, target.position.y + yOffset, -20f);
        transform.position = Vector3.Slerp(transform.position, newpos, CamSpeed+Time.deltaTime);
    }
}

Im looking forward to doing an Attck and Parry System, but dont know how to even start with it. I found a good looking script in the Unity Community forum from 2023.

Hope you can help me to get it working.

best regards
Fabian

One small step at a time is great way to start and also a great way to make continuous incremental progress towards your goal.

When you work, how “good looking” a script is does not matter.

Here is how you can get it working yourself: one step at a time.

Two steps to tutorials and / or example code:

  1. do them perfectly, to the letter (zero typos, including punctuation and capitalization)
  2. stop and understand each step to understand what is going on.

If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.

Imphenzia: How Did I Learn To Make Games:

Here’s more about why random scripts are useless without YOU understanding every part of what you are doing and integrating the script correctly:

As you work, you WILL make bugs, and when that happens, it simply means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.

1 Like

Hey Kurt,

I understand every singel line of my Code I watched a lot of Videos how to learn Unity.

I wanted to reach out to others and ask which fuctions I would need to use to even write an Parry System, how do I detect if I even hit the Opponent (i.g. with an RayCast and and an RayHit), How do I even start to script an opponent, and so on.

With Debugging I had a lot of pain until I found this exact Post, but thanks for the awesome tips!

Hope you can give me some Tips in this regard!

Fabian

Raycasting and RaycastHit are both used for things like hit detection.

Again, start with tutorials. There is a 2D and a 3D physics system and they are completely separate.

If you cannot get this stuff from a tutorial, you will NOT get it no matter what anyone types in this little text box.

If you get stuck, come back here and frame your question like this:

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

If you post code, only post the relevant code and always use the format button above. Do not post photographs of code.

1 Like

Thanks I will take you’re Tips to heart

best regards
Fabian