#💻┃code-beginner

1 messages · Page 686 of 1

wintry quarry
#

what doesn't work with dynamic

formal tide
#

i fixed it thank u 😄

#

i forgot to put that bracket on the last if statemeent

polar dust
#

C# having the ability to allow if statements to not need { } when they only have 1 following line, is a feature I get has utility, but i really wish wasnt a feature

#

im not really sure why its allowed in the first place besides from have a shorthand like if (foo) return;

frail hawk
#

why do you dislike it?

polar dust
#

I find its confusing when reading code where you get lines that lack the braces, mixed in with other code

#

I have to pay more attention to figuring out that two lines that seem like they follow, dont actually follow because theres an brace-less if statement above it

frail hawk
#

on the other hand it saves 2 lines of code, so advantage for reading

polar dust
#

but if it was all surrounded by braces, even for that one line, I can immediately parse the code when reading

#

it really varies on the context of what the surrounding code looks like

#

for very basic early returns out of methods, its not so bad

wanton socket
#

Hi, what's a good way to handle JSON serialisation for abstract classes?
For example my inventory is a simple List<Item> where Item has abstract classes for specific categories, for example Weapons
If a Weapon also has a a damage attribute, whats a good module to use to serialise the list in a way to avoid storing unused attributes on other classes?

#

Something alone the lines of maybe

{
  "itemId": "straight_sword",
  "quantity": 1,
  "extra_attributes": {
    "damage": 1
  }
}
eager elm
wanton socket
#

How would I then serialise my List<Item>?

#

I was thinking about using JsonUtility but I can use Newtonsoft too

eager elm
#

you wouldn't serialize the item itself, just the save data

wanton socket
stuck field
#

Why return a SaveData?

wanton socket
#

Basically if I, for example, wanted a method to convert from my List<Item> to and from JSON I'm not sure what steps I can take when considiering polymorphism

wanton socket
#

Then when I load from JSON I can convert my SerialisableItems to Items using a database to get the prefabs, sprites, etc

stuck field
#

Well I think a string just works better for saving, especially if you're using JSON

wanton socket
#

Yeah, but how do I construct that string

#

I could consturct iti manually

#

but I'm wondering what'd be a modular way to do it since unity has stuff like JsonUtility

#

If I constructed it manually polymorphism wouldn't be a problem since I could directly have a virtual ToJson method that serialised an Item, but I'm just curious if there's a better way to approach it

stuck field
#

Well do you need to use JSON?

#

Where exactly are you saving these? Locally?

wanton socket
wanton socket
#

Oh I should've prefaced its a multiplayer game but I guess thats not totally relevant

#

I'm ok with alternatives like serialising to bytes if converting to JSON would be a headache, but I'd like to convert to JSON for readability more than anything honestly

stuck field
#

I don't think JSON would be needed if you aren't worrying too much about anything other than reading and editing data

wanton socket
#

Right right

stuck field
#

It depends what you're saving though, you mentioned inventory, but is that all?

wanton socket
#

So if I directly serialise to bytes can unity handle polymprhism etc?

stuck field
#

Do you save things like currency too? Or is that also an item?

wanton socket
wanton socket
stuck field
wanton socket
#
[System.Serializable]
public class PlayerData
{
    public List<Item> head;
    public List<Item> torso;
    public List<Item> legs;
    public List<Item> resources;
    public List<Item> weapons;
    public Weapon weapon;
    public Armour headArmour;
    public Armour torsoArmour;
    public Armour legsArmour;
}
wanton socket
stuck field
#

Makes sense, it shouldn't affect it then

wanton socket
#

Then is unity able to serialise a List<Item> properly even if it can be different types of Items?

wanton socket
stuck field
#

You can save only what's in the item class, and load directly into the item class from your other classes

wanton socket
#

I'll probably just do that then and serialise my PlayerData correctly then

wanton socket
stuck field
#

You can also use reflection for things inside the classes themselves if required

wanton socket
#

since Item has stuff like references to prefabs and the sprite, so I could hav ea SerialisableITem that instead has a string ID that can be linked in a catalogue to stuff like the sprites for items

stuck field
#

Yeah, you can have a helper class for figuring all that out

wanton socket
#

Alright I'll see how I can save objects to files then

#

Tysm

#

I'm sure there are utilities to read serialised data in a file if I really need to anyways

stuck field
#

Yeah, would be a bunch as it's a big topic

eternal needle
formal tide
#

hi is this movement controls written well? or is there better way

eternal needle
#

there are hundreds of movement tutorials out there

eternal needle
formal tide
stuck field
eternal needle
formal tide
stuck field
ember tangle
#

Is there a practical use of 'internal' in Unity C#?

rich adder
eternal needle
stuck field
edgy tangle
#

So like if you make a tool and you need scripts within the tool to talk to each other, but you don’t want the end user to have the same level of access

rich adder
#

even without asmdef also, say I have a static function / class / method in Dynamic Library / Class Library, i wouldn't want to necessarily mix that with gameobject code / unity components

eternal needle
#

its an access modifier. they're all useful as a developer and dont affect your actual end product

stuck field
#

I never go below internal for access, just keeps it limited to my own code rather than letting external code access it

rich adder
#

protect yourself from your future self

#

or a code/teamate

charred heart
#

Hi everyone, sorry if i ask this wrong sub. I think my question is beginner so put it here is okay.
I’m reading about vector rotation and I have a question about this formula in the book:
P'=Pcos(θ)+Qsin(θ)

  • Is P′ supposed to have the same length as P?
  • Why is the perpendicular component of P′ equal to Qsin(θ)?

I also included my own derivation in the last image.

wintry quarry
charred heart
#

sorry, could i put it in #unity talk? 🥲

wintry quarry
#

I would say:

  • Yes
  • Not sure what the question means.
charred heart
#

i think I don't really understand how they came up with this linear combination in the first place.I know that any vector in the plane can be written as a combination of two orthogonal basis vectors, but the cos and sin come from no where.

wintry quarry
#

it doesn't explain in what you shared. They are simply showing a rule here of how to create the rotated vector from a linear combination of P and Q (also how to create Q from P) based on the angle theta

#

It doesn't explain how it was derived as far as I can tell

#

but it's a neat trick

hallow acorn
#

hey does somebody know how i can change animator parameters through code?

wintry quarry
#

if you just think about the equation for a circle

#

it's x = sin(theta) and y = cos(theta) for any point at angle theta right?

wintry quarry
#

it's a way of using that simple circle point formula for an arbitrary 2D axis system rather than world x and y

#

so like - in a normal circle your P and Q are just the x and y axis, aka (1, 0) and (0, 1)

#

this is just a generalization of the formula for any such pair of orthogonal vectors

charred heart
#

ahh i see, that actually sounds right.
i just wrote some stuff down, and p' = p * cos(theta) + q * sin(theta) actually matches what i derived with P(x,y) and Q(-y,x)
but because of that, i'm still confused about the length of p' because i assume r is 1.

I think |P| = |P'| = 1 because r = 1. What if r not equal 1? I wll write down some.

lilac cape
#

I'm having an issue with my buttons on my pause screen not working the 2nd time going into the pause screen. Everything works great the first time and I've removed all cleanup and disabling code to see if that was the culprit but still having the issue. Any Ideas on this one? I've been banging my head on it for awhile

Solution was to re-register UI elemets and callbacks every time the pause screen is shown

wintry quarry
charred heart
wind hinge
#

I hate Rider. what is the point of this feature except too confuse people

rocky canyon
#

yea, rider has no chill

rocky canyon
#

riders always been too much for me.. some people swear by it.. but i can't deal with its constant nagging 😅

wind hinge
#

Yeah, the main issue here being i dont know which of the 2 options to use

#

if (target) or if (target != null)

#

🫤

rocky canyon
#

i'd leave it as is

#

if u do target == null u can use an early return

#

thats pretty much the only difference.. (can do away with the extra else) of the if statement

#
if(target == null)
{
     return;
     // rest of code (code u want to run if target *is* assigned
}```
slender nymph
# wind hinge `if (target)` or `if (target != null)`

rider suggests using if(target) because it gives clear intent that you are doing a unity object lifetime check. if(target != null) is not clear intent for the lifetime check because it could be confused with a simple null check

north kiln
#

You don't even have to go into the settings to disable inspections you dislike

rocky canyon
#

i use vscode now b/c its more universal (works out for me and my many projects) but ill keep that in mind 👍

north kiln
#

I'm not sure what's specifically universal about VS Code

rocky canyon
#

i use it for unity, webdev, and embedded work (platform io)

north kiln
# north kiln I disagree completely

Using the implicit conversion is more error prone in my experience, there's plenty of time I've found it making code worse by accidentally converting to booleans when it wasn't meant to be. If I could have it be an error to use it I would!
If you want to do an explicit null check then you would use a modern null checking operator or ReferenceEquals, using an equality operator on a UnityEngine object already communicates intent, because that's default behaviour.
There's no difference in intention when you choose to use implicit boolean conversion (except that in Rider it won't show an implicit conversion icon, which removes that clarity).

acoustic belfry
#

Hey, it is a good idea to use State Enums in the Player or no?

I mean cuz, for an NPC Ai it is... But for a player?

brave robin
#

There's no universal reason not to, it comes down to what you're trying to do

#

If it makes sense to track a certain state on the player, why not?

acoustic belfry
#

The issue is, under my opinion, not fully, but im scared i may repent later

foggy spade
#
using UnityEngine;

public class SpawningScript : MonoBehaviour
{
    [SerializeField] private float Waves = 1;
    [SerializeField] private float SlimeCount = 5;
    [SerializeField] private float SlimeAmount_ToSpawn = 5;
    [SerializeField] private float SlimeAliveCount = 1;

    public SpawnRadius spawnRadius;
    private Vector3 spawnPos;
    [SerializeField] private GameObject Clone;

    [SerializeField] private float Timer = 0f;


    void Start()
    {
        spawnPos = spawnRadius.SpawnPos;
    }

    void Update()
    {
        spawnPos = spawnRadius.SpawnPos;
        Timer += Time.deltaTime;

        if (Timer >= 3f)
        {
            Instantiate(Clone, spawnPos, Quaternion.identity);
            SlimeAliveCount -= 1;
            Timer = 0f;
        }


    }
}
``` for some reason after timer reaches 3 it infinitely spawns clones even after the timer resets to zero
#

sorry for interuptting i didnt notice until i sent my message 💔

rocky canyon
# acoustic belfry Hey, it is a good idea to use State Enums in the Player or no? I mean cuz, for ...

depends.. if ur game depends on knowing what the player is doing.. sure. makes sense to have a state.. say for example you have stamina that lowers when u sprint..
you could just assume ur sprinting by checking the players input..
or u could go ahead and make it a state.. then the stamina would Lower when the player is in a sprinting state.. applies to if ai would need to know.. if the ui wants to display it to you etc..

its really just up to you and ur goals wether or not ull need to keep up with states

acoustic belfry
#

Its like drawing, but drawing logic. Depends on what i need to do

#

Makes sense

#

Thanks :3

wintry quarry
foggy spade
#

ohhh your right

polar acorn
foggy spade
#

hold on let me try something and ill get back to you

acoustic belfry
#

That makes sense

rocky canyon
wintry quarry
rocky canyon
#

ohhhh..

#

ya that ^ lol

foggy spade
#

thank you both <3 i got it working i had the script on the object i was cloning

rocky canyon
#

inception lol

wanton socket
#

My question is more how to construct a json string when dealing with inheritance in unity since jsonutility can't

#

After more googling I'm likely gonna use Newtonsoft with a custom jsonconverter

#

Yeah the dotnetfiddle example you sent seems perfect

eternal needle
wanton socket
#

I have a scriptableobject ItemData with the base attributes

#

Sprite, name, description etc

#

My Item class has a reference to an ItemData

#

When serialising I need to save the ItemData ID, and when deserialising obtain the itemdata from its id

#

But I do have to save custom attributes like quantity or upgrade level

#

I thought a custom converter would be the best for that but I'm not sure

naive pawn
naive pawn
waxen adder
#

I want to modify this script, such that it can instantiate prefabs in the editor view. Purely for design purposes. I'd rather do that instead of doing DrawCube with gizmos (my old method), because it doesn't give an accurate idea of what's actually being built. I asked chatgpt about it and it did give me something that worked, but god was it an ugly implementation. I want to make sure there's a better idea out there before committing to it. The current paste is without any implementation for a "preview" in the editor. If yall need any other info, let me know! https://pastebin.com/y0xciwHW

wanton socket
#

Better example

#

I want some way to essentially omit the dontSerialise field

#

So I can get it back

#

Is just using the JSON ignore property sufficient?

eternal needle
# wanton socket I thought a custom converter would be the best for that but I'm not sure

i still dont think you need any custom converter here. the problem isn't with reading or writing data, it is with knowing what class to associate save data with so you can assign values for the correct item class.
You could even just save a string representing what class it came from (not necessarily the class name but it could be) so you know how to convert it later.

eternal needle
wanton socket
#

So should I then have a method to conveert from Item to ItemSaveData and then serialise that?

#

If so, how do I deal with the inheritance chart: Just mirror the Item inheritance chart with ItemSaveData equivalents and serialise those with newtonsoft?

wanton socket
eternal needle
#

i never used that setting before, will have to try it

wanton socket
#

Tysm

#

Then I can do my ScriptableObject lookup when converting back from ItemSaveData to Item

eternal needle
eternal needle
#

a preview just means you spawn a temporary object. its up to your code to spawn the prefab and destroy it later, making it temporary

wanton socket
#

So itd be like

Armour myHelmet
  ItemData type = (helmet itemdata, id "helmet")
  nickname = "My Helmet"
  upgradeLevel = 10
#

and Id like to serialise this to

waxen adder
wanton socket
#
{
  "$type": "Armour",
  "id": "helmet",
  "nickname": "My Helmet",
  "upgradeLevel": 10
}
#

So that instead of a reference to an Itemdata (which has stuff like sprite, model, etc) I just store an ID which my deserialiser can lookup to get the appropriate itemdata

eternal needle
wanton socket
#

so thats why I thought this 3 class setup made sense

eternal needle
sharp bloom
#
private int _seconds;
public int seconds
{
    get { return _seconds; }
    set
    {
        _seconds = value;
        OnSecondsChanged?.Invoke(_seconds);
        Debug.Log("Ticked!");
    }
}

Why isn't the Debug.Log() firing in my script?

waxen adder
sour fulcrum
#

(also not that it matters but could be worth considering checking if the incoming value is different from current before invoking that event)

eternal needle
sharp bloom
#

Oh right. I set _seconds instead of seconds. Simple mistake xd

eternal needle
waxen adder
#

Because previously I used gizmos and DrawCube to preview a prefab, but that comes with the obvious problem that whatever I want to preview would need to be a cube too

eternal needle
#

i feel like my suggestion above would still apply then. spawn the object once then just adjust it OnValidate if you want. Maybe tie into some editor update functionality if you need to move it along with other objects

sharp bloom
#

Which means this runs every frame

keen dew
#
if(value == _seconds) {
    return;
}
sharp bloom
#

Will that not always be true?

#

Oh I have to do it before I actually set it, I see

pallid nymph
#

And I'd only bother with a special serialization class if it's vastly different. As in, if this is a data class already, you don't also need a savabale data class for it.

wanton socket
#

True true

#

thats good

manic sparrow
wicked bobcat
#

i'm getting an error when trying to use SetActive on a private object and i don't understand why

keen dew
#

and for sprinting you use a different speed cap

#

pretty much what the forum post suggests

keen dew
wicked bobcat
burnt vapor
#

Please properly share all !code

eternal falconBOT
manic sparrow
keen dew
#

That depends on your code but usually you make a boolean that you set true and false when the action starts or ends

wicked bobcat
burnt vapor
keen dew
#

Pretty sure the tutorial doesn't have private object Light

burnt vapor
#

I'd double check what the tutorial does, I very much doubt they used this variable

manic sparrow
#

oooh noted, so might as well ask before i get to it, if i wanted to implement knockback, i'd be giving a set amount of time to go beyond the normal speed cap?

burnt vapor
#

Likely they used GameObject, not object

wicked bobcat
manic sparrow
#

ayt, many thanks

mystic vortex
#
{
    [SerializeField] private AudioSource ding;
        void OnTriggerEnter(Collider other)
    {
        ding.Play();
        Destroy(gameObject);
    }
}```
#

this probably detect all collided, how do usually detect specific target to collide tho?

iron topaz
#

struggling to get my groundchecks to work on all sides of my object, any help appreciated

naive pawn
naive pawn
daring sentinel
#

@naive pawn btw thanks for verifying that my dialogue approach with timeline would work the other day, managed to sort it!

naive pawn
#

uhhhh i have no recollection of that convo

manic sparrow
#

just learned that i can implement character movement with the Character Controller and that the new input manager exists xd. I've been learning based off of Brackey's tutorials, are there any suggestions for updated tutorials?

sharp bloom
#

Can I have multiple identical monobehaviors containing the same event, and have one listener?

naive pawn
#

could you try rephrasing that

#

it's not super clear what the situation you're referring to is

#

multiple components of the same class, or components of multiple classes?

#

what events, unityevents?

sharp bloom
#

So if I have multiple instances of the same gameobject, invoking some custom C# event like OnTrigger, can I have another class listen to the OnTrigger event?

naive pawn
#

OnTriggerEnter/Stay/Exit aren't c# events, they're unity messages

#

or do you mean you're making your own c# event called that

sharp bloom
#

I meant creating custom event with System.Action<> delegate

naive pawn
#

ah, gotcha

wintry quarry
naive pawn
#

so OnTrigger would be non-static?

sharp bloom
#

What happens if I make it static?

#

Does it still work with multiple instances?

naive pawn
#

depends on the effect you want

#

depends on how you define "works"

sharp bloom
#

I don't care which one of the objects invoked the event, I simply need something to happen when any one of them invoked it.

naive pawn
#

if it's static, then all instances of the component share the same event thing, and any instance or static context of some other class can access the event, but all subscribers will be informed if any of the instances invokes the event

sharp bloom
#

Okay gotcha, that should work then

umbral bough
#

Hi, is there a way to remove a component and before removing it also remove all the components that depend on it?
Like, I wanna remove an audio source but can't because there might still be some effects.
Is there no way to forcefully remove it and all the effects at once?
Please @ me and thanks in advance!

naive pawn
#

not exactly your question, but you could restructure it to where you could just destroy the gameobject entirely

#

i feel like that'd be easier

umbral bough
#

I can't

#

working on an audio manager and need to be able to destroy the source only

sharp bloom
#

Put the source on child object and destroy that?

umbral bough
#

and yes, I can keep the track of the effects, of course, but it'd be nicer if there was a 1 liner to do this

naive pawn
umbral bough
naive pawn
#

i'm trying to suggest something that would make your life easier lol

sharp bloom
#

This field is all about workarounds :P But yeah I get it

umbral bough
#

yes, I agree, but lets just say that I am curious to find out if there's a way to do this even if I don't need it

wintry quarry
naive pawn
umbral bough
#

would be nice if unity implemented this feature, will go with child objects ig, thanks

naive pawn
#

would be a lot of work to hide behind a single method name

umbral bough
#

make it 2 methods then, remove dependencies and remove component

eager elm
#

could have them all implement an interface and then use GetComponents<MyInterface>() and destroy them all.

naive pawn
umbral bough
#

good point

umbral bough
naive pawn
#
void SafeRemoveComponent(Component c):
  dependants = new Map<Type, List<Type>>
  components = GetComponents<Component>()
  for (c in components):
    dependencies = c.GetType()
      .GetCustomAttributes(typeof(RequireComponent))
      .SelectMany(rc => [rc.m_Type0, rc.m_Type1, rc.m_Type2])
    for (d in dependencies):
      if (d):
        dependants[d].Add(c)
  for (d in dependants[c.GetType()]):
    for (dc in GetComponents(d)):
      SafeRemoveComponent(dc)
  if (c) Destroy(c)
#

realistically it'd build dependants only once

umbral bough
#

nice

#

just asking, is this pseudo code or sm?
it's def not c# as you used : etc.

naive pawn
#

yeah pseudocode

#

but accurate (hopefully) reflection methods just to show the amount of work

umbral bough
#

I am assuming it could be simplified a bit with recursion but I could be wrong, might give it a try later

naive pawn
#

this already uses recursion

umbral bough
#

oh, my bad, I missed that line

naive pawn
#

otherwise you'd use a stack (instead of utilizing the call stack)

umbral bough
#

I am assuming the unity team could do something lower level to keep the track of dependencies and speed up+simplify this process tho

naive pawn
#

probably could, but seems like they don't do anything of the sort
RequireComponent is documented as only being used for AddComponent

#

also, it'd introduce some problems
if you have components A a1 and A a2, with a B b that depends on A, would deleting a1 also delete b?

umbral bough
#

yeah that's a good point, could be a bool param to determine that tho

naive pawn
#

but it'd be a lot more work

umbral bough
#

if you are refering to performance, an additional method instead that would behave slightly differently

naive pawn
#

i think the practical issue would also be in maintaining it to be not overly inefficient

naive pawn
umbral bough
#

after discussing it for a bit, I can see why it would be a bad idea to have this built in, could lead to some weird stuff in certain cases

twin pivot
#

ive been going over old scripts for the game Im making and look what I found

#

yikes....

naive pawn
#

(float)0.5
hilarious

fallow wind
#

this is the beginner chat right?

#

how to code

naive pawn
#

there are beginner resources pinned, and see !learn 👇

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

sharp bloom
naive pawn
#

it can get worse

twin pivot
#

in other words im redoing the entire thing from scratch!

sharp bloom
#

I mean if it works it works

twin pivot
#

it works until you have to edit it a few months later

naive pawn
#
public Vector2 _pPosGet() {
  _pPosition = new Vector2 { x = this.gameObject.GetComponent(typeof(Transform))?.position.x };
  _pPosition = new Vector2 { x = pPosition.x, y = this.gameObject.GetComponent(typeof(Transform))?.position.y };
  _pPosition = new Vector2 { x = pPosition.x, y = _pPosition.y + (float)((double)5/1e1) };
  return (Vector2)new Vector3(_pPosition.x, _pPosition.y, 0);
}
twin pivot
#

dear god is that boss music I hear in the background

hallow carbon
#

I cant edit my capsule collider

polar acorn
#

Does this object have multiple colliders on it? The edit button doesn't work on multiple colliders acting as a composite so they just disable the button

hallow carbon
#

OH jeah it has 2

#

Ok thanks

manic sparrow
#

when it comes to implementing a sprint cooldown, is using coroutines or delta time better for performance (and possibly multiplayer implementation with state divergences)?

manic sparrow
naive pawn
#

the one that makes your code easy to read and reason with

cosmic dagger
# manic sparrow when it comes to implementing a sprint cooldown, is using coroutines or delta ti...

they're just different methods:
Coroutines are easier to use because the logic is contained inside of it (the coroutine). You don't have to keep track of extra variables, like a timer and the flag to end it, only the Coroutine reference. Starting many coroutines can be difficult to track and a coroutine will act on the next frame after its delay passes, so it's not as accurate.

Using deltaTime and an Update offers more precision as it checks and can update every frame. You can handle many timers at once instead of in a sequential order, but you have to keep track of a flag and a timer variable . . .

manic sparrow
#

alright, in that case ill go for delta time since i dont mind learning about using flags and timers

#

thanks!

leaden bluff
#

Hey I have been working on a Plane movement, above is the PlayerController script.
My plane basically has to move in the forward direction wrt it's Local Axis but it is moving the World Axis irrespective of its rotation
It'd be great help if someone can clarify this issue 🙂

eternal falconBOT
leaden bluff
#
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float speed = 5f; // Speed of the player movement
    [SerializeField] private float initialThrust; // Initial thrust applied to the player when spawned
    [SerializeField] private float rotationSpeed = 100f; // Speed of rotation for the player
    [SerializeField] private float turnSpeed = 10f;
    [SerializeField] private float yaw;
    private PlayerInput playerInput;
    [SerializeField] private Rigidbody playerRb;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        playerInput = GetComponent<PlayerInput>();
        playerRb.AddForce(transform.forward * initialThrust, ForceMode.Impulse);
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        //Apply continuous forward movement to the player
        PlayerRotation();
        Debug.Log(transform.forward);
    }
    void PlayerRotation()
    {
        // Get the input vector from the player input system and perform movement and rotation
        Vector2 moveVector = playerInput.actions["Move"].ReadValue<Vector2>();
        yaw += Mathf.Clamp(moveVector.x * turnSpeed, -90, 90);
        Quaternion targetRotation = Quaternion.Euler(-45f * moveVector.y, yaw, -45f * moveVector.x);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.fixedDeltaTime * rotationSpeed);
        Vector3 forwardDir = transform.forward;
        playerRb.AddForce(forwardDir * speed * Time.fixedDeltaTime);
    }

}
meager crescent
#

can someone help me with my code. The camera is smooth when I run on windows but when I put it as a web version (itch.io) it jitters a lot, how do I fix that?

using UnityEngine;
using UnityEngine.UI;

public class PlayerCamera : MonoBehaviour
{
    [Header("Looking Settings")]
    [SerializeField] private Transform player;
    public float mouseSensitivity { get; private set; } = 400f;
    float xRotation = 0f;
    float mouseX;
    float mouseY;

    [SerializeField] private Slider sensitivitySlider;


    // Update is called once per frame
    void Update()
    {
        //Changes the sensitivity of the mouse to the slider's in the settings
        mouseSensitivity = sensitivitySlider.value * 10f;

        //Gets the input from the mouse
        mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

    }

    void LateUpdate()
    {
        //Subtracting the mouseY moves the camera up/down naturally
        xRotation -= mouseY;
        //Clamping the camera prevents it from doing a whole 360 over the player
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        //Changes only the up/down angles of the cameraa
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

        //Rotates the player left/right with the camera
        player.Rotate(Vector3.up * mouseX);
    }
}```
if you want to check the bug https://poltergeiststudios.itch.io/frozen-yougurt
itch.io

Serve human ice-cream to monsters! Play in browser or download for Windows!

naive pawn
meager crescent
#

okk ill do that

hallow acorn
#

hey do i cause any problems when flipping my 2d player by rotating it on the y axis so i dont have to make every animation twice?

naive pawn
#

depends on how you do a lot of other stuff

hallow acorn
#

i hate that sticker but your prolly right

naive pawn
#

it's taken from a video lol

sour fulcrum
#

(Chris has now been shot in the head for linking a reactionary meme)

hallow acorn
#

IT HAS ITS OWN DOMAIN????

hexed terrace
#

calm down.

exotic forge
#

lol. I think it's my preferred method, since it flips other things for you. Like... ahh it's been a while since I was in my 2d project, but I think vector2.right will change direction when your transfrom is rotated, making attack and walljump raycasts convenient and easy

naive pawn
#

yeah, a lot of "how to ask for help well" websites do
see also: nohello, dontasktoask, xyproblem, etc...

naive pawn
exotic forge
#

riiiight

#

ty ty

hallow acorn
#

i think illtryitandsee

naive pawn
#

for a top-down view? thonk

#

i think just flipping the sprite (for the graphical aspect) would do better for that since flipping the transform wouldn't work for up/down

exotic forge
#

the only other thing I can think of to keep in mind is some shaders will be finicky. You want to make sure you're rendering both sides of sprites, since you're flipping it over, and also disable depth write, so it doesn't toggle behind/infront of your character

#

oh yeah, also that

hallow acorn
#

i hate animating so much this animator is so complicated

exotic forge
#

as long as the sprite flip isn't controlled by the animator, it should be fine

hallow acorn
#

ok ill try

naive pawn
#

oh wait i misread

#

i thought you said "can i do it using animations" lol

wicked fiber
#

does anybody know about how I would make an enemy take damage from say, a bullet?

naive pawn
#

so yeah what valentine said

naive pawn
wicked fiber
#

ok

hallow acorn
exotic forge
#

lolol

hallow acorn
#

works now

#

theres no better feeling than somethign working (almost) first try

exotic forge
#

right???

hallow acorn
#

i mean theres a couple bugs left but the piles getting a lot smaller

naive pawn
#

don't worry, it'll get bigger soon

hallow acorn
#

thats why im doing animations right now

#

im scared

meager crescent
#

maybe the issue is in my movement script?

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    [SerializeField] private Rigidbody rb;

    [SerializeField] private Transform spawnPoint;

    [Header("Walking Settings")]

    [SerializeField] private float walkSpeed = 30f;
    
    [SerializeField] private float maxSpeed = 15f;

    private Vector3 moveDirection;

    void Start()
    {
        transform.position = spawnPoint.position;
    }


    void Update()
    {
        //Gets the WASD input
        float inputX = Input.GetAxis("Horizontal");
        float inputZ = Input.GetAxis("Vertical");

        //Makes the direction relative to the players transform
        moveDirection = transform.right * inputX + transform.forward * inputZ;

        //Makes the Y direction to 0 so that it doesnt move upwards
        moveDirection.y = 0f;

        //Normalizes the movement so that it does not go faster diagonally
        moveDirection = moveDirection.normalized;

       
    }

    [System.Obsolete]
    void FixedUpdate()
    {
        //Makes new velocity using the direction and the speed
        Vector3 velocity = moveDirection * walkSpeed;
        //Makes the y velocity to the original so that the gravity/jumping doesnt change
        velocity.y = rb.velocity.y;

        Vector3 flatVelocity = new Vector3(velocity.x, 0f, velocity.z);

        //If the force is less than the max amount of forced used
        if (flatVelocity.magnitude > maxSpeed)
        {
            //Moves the player based on the input by the move force
            flatVelocity = flatVelocity.normalized * maxSpeed;
            
        }
        
        rb.velocity = new Vector3(flatVelocity.x, rb.velocity.y, flatVelocity.z);

    }
}
exotic forge
#

if it works well on one platform but not on a webbuild, I doubt the problem is in the code

naive pawn
#

why is it marked obsolete

exotic forge
#

also, where did you get this code?

swift elbow
ebon thistle
#

how can i make an object rotate to the player-object

swift elbow
#

do you mean move and rotate or just roll?

rich adder
naive pawn
ebon thistle
swift elbow
naive pawn
#

i'm talking about FixedUpdate being marked with [System.Obsolete]

polar acorn
# naive pawn ...what?

If you get the warning for using an obsolete property, like velocity, then you can choose to mark the whole method as obsolete to make the error go away instead of fixing it

#

Which is not a good idea

naive pawn
#

won't that just make an error in the build

polar acorn
#

Yes. Which is why it is not a good idea

naive pawn
#

gotcha

polar acorn
#

It just kicks the can further down the road

swift elbow
runic lance
#

I don't think it will cause an error unless you pass isError: true 🤔

exotic forge
polar acorn
#

I haven't actually tried to build with an obsolete Unity Message function, I don't know if it would give a build error or simply fail to do what you expect. Either way I'd suggest changing it

hallow acorn
polar acorn
naive pawn
exotic forge
#

also the animator controller you're passing in is private, so how are you setting that ref?

exotic forge
#

oh. mb

hallow acorn
polar acorn
naive pawn
exotic forge
#

you can just do a debug.Log chain to figure out what's what

#
if(playerController == null) Debug.Log("pC is null");
if(playerController.GetComponent<Animator>() == null) Debug.Log("anim is null");

etc

hallow acorn
naive pawn
#

that doesn't cause an error, no

#

it's just a nightmare for readability

#

(though it could be an issue in some languages where types and variables kinda occupy the same space, like js or c/c++)

hallow acorn
#

oh

#

maybe because i tried getting a component from a component

#

ill try referencing the player and not the PlayerController class

exotic forge
#

i think it should work betterthinking

#

as long as they are on the same game object

#

I can't recall, tho

polar acorn
#

Calling GetComponent on a component is the same as calling it on that component's GameObject

naive pawn
naive pawn
hallow acorn
#

it works now but maybe because im referencing the player through a serializefield now and not through code which seems to not have worked

naive pawn
#

you're still referecning the player through code

#

you set a reference via the serialized field

#

you never set the variable before

polar acorn
#

You can 100% use a variable of type playerController here.

You just need to actually set it to something

hallow acorn
#

how do i set it?

naive pawn
#

=

#

or i mean, since you're already doing the CompareTag, you could just GetComponent from the collision component

polar acorn
meager crescent
ember tangle
#

Im getting a warning when doing this but it does actually work, is there a reason not to do null propagation like this?

[SerializeField] private Button restart;

private void Start()
{
    restart?.onClick.AddListener(ClickRestart);
}

private void ClickRestart()
{
    SceneChange.instance.LoadScene(Scene.Combat);
}```
#

restart?.onClick.AddListener(ClickRestart); this line gets a unity engine warning but it works the way I want it to

polar acorn
slender nymph
#

it would end up being a Missing Reference Exception rather than Null Reference Exception. unity throws the MissingRE when accessing a destroyed object

ember tangle
#

So if I guarantee that it will never be possible to access these buttons during cleanup I'm fine?

polar acorn
#

You should just use if (restart) instead of the ?. operator

ember tangle
#

if (restart) restart.onClick.AddListener(ClickRestart); correct?

slender nymph
#

even if you are sure it can't happen, you still shouldn't use the null conditional operator with unityengine objects. it is better to completely prevent the issue rather than just hoping it won't happen

ember tangle
#

alright

naive pawn
ember tangle
#

What I posted is an abridged version of my class. I realized I had coded all the buttons too many times so I just made a ButtonController class that only works if there are null checks. ```public class ButtonController : MonoBehaviour
{
[SerializeField] private Button mainMenu;
[SerializeField] private Button newGame;
[SerializeField] private Button loadGame;
[SerializeField] private Button restart;
[SerializeField] private Button settings;
[SerializeField] private Button exitGame;
[SerializeField] private Button saveGame;

private void Start()
{
    if (newGame) newGame.onClick.AddListener(ClickNewGame);
    if (mainMenu) mainMenu.onClick.AddListener(ClickMainMenu);
    if (restart) restart.onClick.AddListener(ClickRestart);
    if (loadGame) loadGame.onClick.AddListener(ClickLoadGame);
    if (settings) settings.onClick.AddListener(ClickSettings);
    if (exitGame) exitGame.onClick.AddListener(ClickQuit);
    if (saveGame) saveGame.onClick.AddListener(ClickSaveGame);
}

private void ClickRestart()
{
    SceneChange.instance.LoadScene(Scene.Combat);
}

private void ClickMainMenu()
{
    SceneChange.instance.LoadScene(Scene.MainMenu);
}

private void ClickNewGame()
{
    SceneChange.instance.LoadScene(Scene.Combat);
}
private void ClickLoadGame()
{
    Debug.Log("ClickLoadGame()");
}

private void ClickSaveGame()
{
    Debug.Log("ClickSaveGame()");
}

private void ClickSettings()
{
    Debug.Log("ClickSettings()");
}
private void ClickQuit()
{
    Debug.Log("ClickQuit()");
    #if UNITY_EDITOR
        EditorApplication.ExitPlaymode();
    #else
                        Application.Quit();
    #endif
}```
#

attached to anything with buttons

#

probably clunky but its made me type less

#

the idea being that often most of the buttons will be null or I guess "unity null"

polar acorn
#

You know, you could set these functions in the inspector for the buttons without needing to assign a function to them in start

#

You can put this script somewhere central and have all those buttons call functions on it

ember tangle
#

see that probably makes a lot of sense

naive pawn
obtuse zenith
#

Does anybody know why my text doesnt go away?

using UnityEngine;
using TMPro; // Nodig voor TextMeshPro

public class Pickup2 : MonoBehaviour
{
    [Header("Effects")]
    public GameObject particleEffectPrefab;

    [Header("UI")]
    public GameObject pickupMessageUI; // Koppel hier het UI-element in de Inspector

    public float messageDuration = 2f; // Hoelang de boodschap zichtbaar is

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            if (particleEffectPrefab != null)
            {
                Instantiate(particleEffectPrefab, transform.position, Quaternion.identity);
            }

            if (pickupMessageUI != null)
            {
                StartCoroutine(ShowPickupMessage());
            }

            Destroy(gameObject);
        }
    }

    System.Collections.IEnumerator ShowPickupMessage()
    {
        pickupMessageUI.SetActive(true);
        yield return new WaitForSeconds(messageDuration);
        pickupMessageUI.SetActive(false);
    }
}
```cs
eternal falconBOT
obtuse zenith
polar acorn
obtuse zenith
polar acorn
obtuse zenith
polar acorn
#

Then you would need the timer to be on an object that does not get destroyed instead of this one

naive pawn
#

start the coroutine on something else or disable the graphics first and destroy it later

ivory bobcat
#

If you want the coroutine to finish before destroying the object, perhaps disable the renderer/collider and move destroy to the end of the coroutine? UnityChanHuh

obtuse zenith
# naive pawn start the coroutine on something else or disable the graphics first and destroy ...
using UnityEngine;
using TMPro; // Nodig voor TextMeshPro

public class Pickup2 : MonoBehaviour
{
    [Header("Effects")]
    public GameObject particleEffectPrefab;

    [Header("UI")]
    public GameObject pickupMessageUI; // Koppel hier het UI-element in de Inspector

    public float messageDuration = 2f; // Hoelang de boodschap zichtbaar is

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            if (particleEffectPrefab != null)
            {
                Instantiate(particleEffectPrefab, transform.position, Quaternion.identity);
            }

            if (pickupMessageUI != null)
            {
                StartCoroutine(ShowPickupMessage());
            }

            gameObject.SetActive(false);

            Destroy(gameObject, messageDuration);
        }
    }

    System.Collections.IEnumerator ShowPickupMessage()
    {
        pickupMessageUI.SetActive(true);
        yield return new WaitForSeconds(messageDuration);
        pickupMessageUI.SetActive(false);
    }
}

Like this?

#

cause it doesnt work yet

ivory bobcat
#

Or have the coroutine be in a different script and attached to the ui message object. Where you'd call a method from the other script providing some string message and duration. Letting that other script manage the coroutine and allowing you to immediately destroy this object etc
No one way to go about this.

ivory bobcat
#

And move destroy into the coroutine.

obtuse zenith
#

Its still not working... Could someone maybe add something to the code or rewrite it?

#

cause everything i do doesnt work

hallow acorn
#

hey should i call rb.velocity in fixed update and input in Update or should i put it somewhere else?

ivory bobcat
# ivory bobcat Disable the collider and renderer. Not set the object inactive.
  • Create a field called collider and have it referenced in Start using Get Component
  • Create a field called renderer and have it referenced in Start using Get Component
  • Replace your Destroy call after the inner-most if-statement with the disabling of the two components
collider.enabled = false; 
renderer.enabled = false;```
- Call the Destroy at the end of the coroutine (no delay necessary)
```cs
Destroy(gameObject);```
@obtuse zenith
rugged beacon
#

Im using IpointerEnter and Exit to change cursor when hover
but if the UI just turn off, like disable the cursor doesnt change back
do i just make like an edge case with OnDisable setCursor = null back? feels wrong. how do you guys handle cursor changes

vocal quiver
#

Hello guys for some reason my item's rotation and position keeps changing during playtime. I disabled all scripts and colliders but the issue is still there does anyone know what is causing this?

rugged beacon
#

constrain in rigidbody

#

freeze rotation

vocal quiver
#

hmm but wont I need it for when I am dropping the item??

vocal quiver
rugged beacon
#

it doesnt lock the obj rotation ?

vocal quiver
#

nope it should but the object is still changing values in terms of rotation and position

#

also I have the setup like this. Only IronRod_item has this issue the weaponholder and IronRod prefab remain unchanged

rugged beacon
#

which one has the above rigidbody

vocal quiver
#

the IronRod_item

rugged beacon
#

ngl idk

vocal quiver
#

its over for me 😭

#

thx for your time tho

vocal quiver
#

sure ill give it btw how do you write code on discord

eternal falconBOT
rugged beacon
#

he disabled all the scripts in that object tho

rich adder
vocal quiver
rich adder
#

Disabled scripts can still run functions

#

disabling just disables unity events

rugged beacon
rich adder
vocal quiver
#

,,,Cs
private void Drop()
{
equipped = false;
slotFull = false;

    transform.SetParent(null);

    rb.isKinematic = false;
    coll.isTrigger = false;

    rb.velocity = player.GetComponent<Rigidbody>().velocity;

    rb.AddForce(fpsCam.forward * dropForwardForce, ForceMode.Impulse);
    rb.AddForce(fpsCam.up * dropUpwardForce, ForceMode.Impulse);

    float random = Random.Range(-1f, 1f);
    rb.AddTorque(new Vector3(random, random, random) * 10);

    gunScript.enabled = false;
}

}

#

damn it i messed it up 💀

rich adder
#

Do you have a video of the issue.?

vocal quiver
#

sure ill send a recording

dusty whale
#
using UnityEngine;
using UnityEngine.SceneManagement;
public class gamemanagerscript : MonoBehaviour
{
    public static gamemanagerscript instance;
    public GameObject pausemenugameobj;
    Canvas pausemenucanvas;
    private bool paused = false;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }


    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape) && !paused)
        {
            Debug.Log("escape pressed");
            pausegame();
        }
        if (Input.GetKeyDown(KeyCode.Escape) && paused)
        {
            resumegame();
        }

    }

    public void pausegame()
    {
        pausemenugameobj.SetActive(true);
        pausemenucanvas = instance.pausemenugameobj.GetComponent<Canvas>();
        Debug.Log("func entered");
        pausemenucanvas.enabled = true;
        Debug.Log("pausemenugameobj is null? " + (pausemenugameobj == null));
        paused = true;
        Time.timeScale = 0f;
    }

    public void resumegame()
    {
        pausemenucanvas.enabled = false;
        paused = false;
        Time.timeScale = 1f;
    }

    // Update is called once per frame
    public void returntomainmenu()
    {
        SceneManager.LoadScene(0);
    }
}
dusty whale
#

and/or anyone really ive been going at this for literally 3 hours

vocal quiver
rich adder
rugged beacon
#

scripts in weaponHolder ?

vocal quiver
vocal quiver
#

interestingly the weaponholder is unchanged

rugged beacon
#

Disabled scripts can still run functions

if this is trrue you should show the script item script code too

vocal quiver
#

alr but im pasting it raw idk how to paste code like that 💀

rich adder
#

Did uiu animate the stick with animator/animation?

tidal tide
#

The code seems fine and you're enabling and disabling the pause object well, which object is this code on?

vocal quiver
rugged beacon
#

!code

eternal falconBOT
dusty whale
#

wait @tidal tide

#

i think i found it

#

i wrote this
Debug.Log("Scene: " + SceneManager.GetActiveScene().name);
Debug.Log("pausemenugameobj scene: " + pausemenugameobj.scene.name);

#

and they didnt match

#

that means that the gameobj im trying to activate is in another 'scene' (which is 'DontDestroyOnLoad' while the actual scene is 'Level 1'

#

Idk why this happens but apparantly unity dont say anything abt it and thinks its an active gameobj and that it exists which doesnt return a null error but i cant alter/change it at all

tidal tide
#

Ooh I understand the issue, so your references are not being carried over to the next scene, but I'm surprised it didn't throw a null error as well

#

Well done finding the solution though

vocal quiver
dusty whale
#

and i think this happens because the pausemenu is a child to the gamemanger gameobj which has a dontdestroyonload on the whole gameobj

dusty whale
vocal quiver
#

btw there is another script called gunScript but it is just a dummy placeholder the script has no lines inside

rich adder
vocal quiver
#

yea its suppose to allow me to pick up and drop the stick

rich adder
vocal quiver
#

the issue stays

#

its even disabled in the video

rugged beacon
#

just to be clear there is no script in the WeaponHolder parent object ?

vocal quiver
#

yes absolutely no script

rugged beacon
#

nothing else reference to that obj beside itself?

vocal quiver
#

yup

rugged beacon
#

theres seem to be one other gunscript

vocal quiver
#

thats empty

rugged beacon
#

ngl idk

vocal quiver
#

man should I just delete the item and start over?

rugged beacon
#

delete the one at a time a guess, and im guessing removing the rigidbody will resolve it

vocal quiver
#

i did remove rb doesnt help so yea best option is to restart

#

thx for your time guys @rich adder @rugged beacon i will come back if i found the answer

rich adder
vocal quiver
#

havent done that lemme try

rugged beacon
#

i ddint see any animator fr

vocal quiver
#

hes talking abt the ones im using in the arms and nope doesnt work

rich adder
#

hmm I suppose try redo one thing at a time and see where it goes wrong

vocal quiver
#

guys i found the issue its when I change the interpolate to exterpolate thats when the issue arrises now idk why that happens but i was follwing a tutorial and the person said to put that setting on

rich adder
vocal quiver
#

yea i turned it off

queen adder
#

My concern is if theres code that's running that doesnt need to be anymore (when you reach maximum falling speed). does that make sense?

ivory bobcat
coarse stag
#

Unity uses C#, but any way to make it us C++?

#

Maybe a plug in?

queen adder
#

Nevermind, I'll keep thinking about it

rich adder
coarse stag
#

Core API? CONFUSED UNGA BUNGA

rich adder
#

you can make interop calls / libraries to C++ but thats not what the API built for

rich adder
#

if you want to code C++ switch to unreal

high summit
#

        //black the screen
        mycanvas.enabled = true;

#

Anybody know why this canvas wont enable with code?

ivory bobcat
high summit
rich adder
high summit
#

I'm basically trying to just 'check' this box to enable it

rich adder
high summit
#

I thought that but it wont accept SetActive

rich adder
#

myComponent.gameObject.SetActive

high summit
#

That makes sense, thanks folks

rocky gale
#

np

high summit
#

Is therre a trick to getting videos to work?

#

Want a looping video as my 'main menu' background

#

But can't get it to show up at all

#

Ah my bad

#

I see the iissue

oblique chasm
#

Is it possible to expose a vector2 to the editor with some kind of marker similar to exposing variables to the inspector. Like, could I, in a script without any additional addons or objects, when I place an object in a scene, have a marker pop up on the scene view that I can drag around that I can use to affect my code?

rich ice
#

i think you'd need to use an #↕️┃editor-extensions. although im not 100% sure if you can do it without. i'd be interested in knowing if there's a way as well 👀

oblique chasm
#

I know I can use another object in the scene and pull it's pos info to fill the vector2, but if there's a way to do it without adding an additional object to the scene, even if I remove it at runtime.

rich ice
#

im not entirely sure myself. im interested in knowing aswell, i've never really tried.
until someone else answers though i think Gizmos or Handles might be a good place to try looking

#

ok so i looked into a bit myself and it seems like yeah, you cant do it without an editor extension.
good news it that the code is pretty short atleast
there's some example code in the unity docs

#

there's a lot of other useful handles here too. i somehow never knew these existed UnityChanOops

wicked fiber
#

Hello, I just forgot if the characters "||" was as well as or instead of

#

in a bool

rich ice
#

i believe that is the "or" operator

#

so, if either condition is true the code will run

#

"as well as" (usually called and) is written as &&
"instead of" (usually called not equal) is written as !=

wintry quarry
rich ice
#

(someone might need to correct me on whether its 1 or 2 of the symbol, i get that wrong pretty often)

wicked fiber
#

I found it out

wintry quarry
#

&& is "and"
|| is "or"

wicked fiber
#

Oh thanks!

#

Thats the response I was looking for

#

Take that google

wintry quarry
rich adder
wicked fiber
#

oh ):

#

wait youre the guy that helped me before!

rich adder
#

probably lol

formal tide
#

Guys i realized FixedUpdate is more smooth for WASD controls but space for jumping is not that smooth

#

Update is more smooth for Jumping

stuck field
#

FixedUpdate shouldnt be used for inputs

formal tide
#

Is it correct or am i wrong

teal viper
#

If it's input querying, that should be in normal update.

formal tide
#

!code

eternal falconBOT
formal tide
#

Space is not working well inside fixedupdate. Wasd worked well

rich adder
acoustic belfry
#

Hey i have a question, why i have to use a coroutine for the delays? Why dont make delays work naturally?

I mean cuz is very annoying to make a value timer and an inf scenario until is zero for make it, instead of just putting delay

wintry quarry
#

How would it know when to stop and go render the next frame, for example?

acoustic belfry
#

I mean, why coroutines? Idk how to explain it

Wait, i think now makes sense

#

Like an action

#

A delay would pause the whole system

#

Meanwhile a coroutine is just, an action

#

But anyways, apart of coroutines, whats a simple way to make it wait?

wintry quarry
#

Async

acoustic belfry
#

Huh?

wintry quarry
acoustic belfry
#

Why i neveard heard of this?

I only read abt coroutines or value -= time.Deltatime

sour fulcrum
#

Cuz usually it’s overkill

#

And not simpler

acoustic belfry
#

Ooof

When what is it?

Just coroutines and value -= time.deltaTime?

#

Idk, i just want a simple way to make sequences and stuff

rich adder
acoustic belfry
#

O h

#

Ok

#

I mean cuz

I have a combo melee attack that instead of the normal melees that are a click, this one remains dangerous for a sec

#

How i can do so?

rich adder
#

a timer?

acoustic belfry
#

Just the value thing?

rich adder
#

i don't see the point of using async here

acoustic belfry
#

Is not bad, but my problem is im flooded with values

#

And hardcoding values i feel like i might repent

#

Yet that would clean stuff up

rich adder
acoustic belfry
#

Havent tested yet. But the thing is affected in an instant.

Im not at my pc currently

Later i will reply with the issue explained

Sorry;-;

sour fulcrum
#

Can I make new objects at runtime off of ISerializationCallbackReciever.OnAfterDeserialize? I know it’s an issue during onbefore, atleast in an editor context

#

Actually also curious what the order of execution is there, does awake run before that callback?

foggy spade
#
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;

public class ScreenShake : MonoBehaviour
{
    public float ShakeDuration = 0.5f;
    public float Magnitude = 2f;
    private Vector3 origPos;
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            StartCoroutine(Shake());
        }
    }

    IEnumerator Shake()
    {
        origPos = transform.position;
        float elapsed = 0f;
        while (elapsed < ShakeDuration)
        {
            float offsetX = Random.Range(-1, 1) * Magnitude;
            float offsetY = Random.Range(-1, 1) * Magnitude;
            transform.position = origPos + new Vector3(offsetX, offsetY, 0);
            elapsed += Time.deltaTime;
            yield return null;
        }
        transform.position = origPos;
    }
}

``` how can i make the shake to the camera smoother
#

ignore the high magnitude i changed it

oblique chasm
#

Getting an error saying "cannot declare public variable of static type 'Path', anyone know why? I'm following a tutorial line for line, shouldn't be any errors unless I missed something.

public class PathManipulatorTool : EditorTool
{
    public override void OnToolGUI(EditorWindow window)
    {
        if(!(window is SceneView)) 
            return;

        foreach(var obj in targets)
        {
            if (!(obj is Path path))
                continue;
            for (int i = 0; i < path.NumberOfControlPoints; i++)
            {
                Vector2 point = path.GetControlPoint(i);

                EditorGUI.BeginChangeCheck();

                point = Handles.PositionHandle(point, quaternion.identity);
            }
        }
    }
}```
stuck field
stuck field
foggy spade
#

thank you!! ill check it out

oblique chasm
ivory bobcat
#

Perhaps select a new position every half second (500ms) and have your position move towards that point, if frequency and interpolation is the concern.

stuck field
#

All that'd do would move the camera to one random pos, rather than smoothly shake it

#

Lower intervals so it shakes works though

ivory bobcat
stuck field
#

No?

#

You're just saying move to one position

#

Not several

#

It wouldn't lead to the result that's wanted

fallow wind
#

chat, i copied this from 8 different youtube tutorials, and some tiktok

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public GameObject playerObject;
    public float flapPower = 6.928f;

    Rigidbody2D rb;
    bool initialized = false;
    int counter = 0;
    List<string> debugMessages = new List<string>();

    void Awake()
    {
        playerObject = GameObject.Find("bird");
        if (playerObject != null)
        {
            rb = playerObject.GetComponent<Rigidbody2D>();
        }
        else
        {
            rb = GetComponent<Rigidbody2D>();
        }
    }

    void Start()
    {
        StartCoroutine(StartLater());
    }

    IEnumerator StartLater()
    {
        yield return new WaitForSeconds(0.00001f);
        initialized = true;
    }

    void Update()
    {
        counter++;
        if (counter % 2 == 0 && initialized && Input.anyKey)
        {
            if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0) || Input.touchCount > 0)
            {
                Vector2 flap = new Vector2(Mathf.Sin(Time.time * 0.01f) * 0.001f, flapPower);
                rb.velocity = new Vector2(0.00001f, 0.00001f);
                StartCoroutine(ApplyForceNextFrame(flap));
            }
        }
    }

    IEnumerator ApplyForceNextFrame(Vector2 force)
    {
        yield return new WaitForEndOfFrame();
        if (rb != null)
        {
            rb.AddForce(force / 1.000001f, ForceMode2D.Impulse);
        }
    }
}
#

is that good?

#

its kinda laggy tho

stuck field
#

I would bet

#

You should learn for yourself and make it properly

#

A lot of free resources at !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

rich adder
ivory bobcat
# foggy spade ```using System.Collections; using UnityEngine; using UnityEngine.AI; using Unit...

I would do something like this, given the original:cs private Vector3 offset; public float speed = 5f; public float delay = 0.500f IEnumerator Shake() { origPos = transform.position; offset = Vector3.zero; var target = StartCoroutine(Target()); var move = StartCoroutine(MoveTowards()); yield return ShakeDuration; StopCoroutine(target); StopCoroutine(move); transform.position = origPos; } IEnumerator Target() { while(true) { offset.x = origPos.x + Random.Range(-1, 1) * Magnitude; offset.y = origPos.y + Random.Range(-1, 1) * Magnitude; yield reutrn delay; } } IEnumerator MoveTowards() { while(true) { transform.position = Vector3.MoveTowards(transform.position, offset, speed); yield return null; } }(no ide - errors may be present)

stuck field
#

Errors are present, but that's a given, also your coroutines never break, they'll continue endlessly unless the object gets disabled, and that's terrible for performance as each time you shake the camera, you end up stacking another infinite loop on the pile, which will eventually cause massive lag

#

Now you stop them, ignore that, but still not a great way as it'd snap back to the start pos

#

Very overcomplicated in my opinion

acoustic belfry
#
 void HandleValeriaMachete()
  {
      Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
      Vector3 direction = mousepos - transform.position;
      machetepos.rotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg));
      float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
      machetepos.position = transform.position + Quaternion.Euler(0, 0, angle) * new Vector3(machetedistance, 0, 0);
      machete_swingTimer -= Time.deltaTime;
      
      if (Input.GetMouseButtonDown(1) && machete_swingTimer <= 0)
      {
          machete_swingTimer = machete_swingSpeed;
          if (isDashing)
          {
              currentStyle = meeleStyle.DashSlash;
          }
          else if (!valeriaTocoPasto())
          {
              currentStyle = meeleStyle.AirSlash;
          }
          else
          {
              currentStyle = meeleStyle.Combo;
          }
          switch (currentStyle)
          {
              case meeleStyle.Combo:
                  MeleeAttack(machetepos, attackRange, meleeDamage);
                  break;
              case meeleStyle.AirSlash:
                  MeleeAttack(transform, attackRange + 5, meleeDamage + 1);
                  break;
              case meeleStyle.DashSlash:
                  MeleeAttack(machetepos, attackRange, meleeDamage + 3);
                  rb2D.linearVelocity = new Vector2(valeriaMove * dashSpeed, rb2D.linearVelocity.y);
                  break;
          }
      }
  }```
#

in airSlash the player does a spinning animation, how i can make it that it hurts anything that touches it (the function remains) until it ends?

rich adder
#

You don't have to use animation at all, you can also base it on specific time of effect

acoustic belfry
#

time of effect?

rich adder
#

timer i guess

acoustic belfry
#

oh! ok, thanks :3

#

hey also, how i can make a movement burst?

i mean, i tried to make a dash system for my player, but instead of making it dash, it makes it sprint

#
 void ValeriaMovement()
 {
     if (Input.GetKey("d") || Input.GetKey("right"))
     {
         valeriaMove = 1f;
     }
     else if (Input.GetKey("a") || Input.GetKey("left"))
     {
         valeriaMove = -1f;
     }
     else
     {
         valeriaMove = 0f;
     }
     dashTime = Mathf.Max(dashTime - Time.deltaTime, 0f);

     if (Input.GetKey(KeyCode.LeftShift) && valeriaMove != 0)
     {
         if (dashTime <= 0)
         {
             dashTime = dashCooldown;
             dashTimer = dashDuration;
             isDashing = true;
             spriteRenderer.color = Color.cyan;
             rb2D.linearVelocity = new Vector2(valeriaMove * dashSpeed, rb2D.linearVelocity.y);
             return;
         }
     }
     else
     {
         rb2D.linearVelocity = new Vector2(valeriaMove * runSpeed, rb2D.linearVelocity.y);
     }
     if (isDashing)
 {
     dashTimer -= Time.deltaTime;
     if (dashTimer <= 0f)
     {
         spriteRenderer.color = Color.white;
         isDashing = false;
     }
 }
 }```
#

what im doing wrong?

rich adder
#

the dash code and the move look the same

#

also there are many different types of dash you can do, freeform, specific distance, specific amount of time, etc

acoustic belfry
#

huh? how each one works? Im just trying to make the basic, Hollow Knight-like

#

i just need it to burst movement to the side the key is pressed

rich adder
#

you tried just doing an AddForce Impulse for starters?

#

thats the freeform version more or less

acoustic belfry
#

i heard AddForce relies on friction so thats why im using linearVelocity

rich adder
#

you could probably do a float.movetowrds or something during a coroutine

acoustic belfry
#

honestly i thought linearVelocity moved the player to the direction + the speed of the value like a burst, and yet is in fixedUpdate, it would be infinetly making it look like is walking...but since i tested this..something weird happened

#

like, doesnt dash well

acoustic belfry
#

or maybe i should just use AddForce

#

idk, im just trying to make it the most simple yet efficient posible

rich adder
#

there isn't a methodology set in stone, you have to do what feels right/proper for your project

acoustic belfry
#

simple, yet workable

#

i mean, i want something i can read

rich adder
#

lookup a few dashes and how others do it then see whatever you can make your own out of it

#

each one has its own pros and cons

#

think most recent I did was a specific amount of time, but with that you would need to stop it at a wall with rays..so you don't feel stuck cause its still dashing into a wall..

acoustic belfry
#

oh

acoustic belfry
rich adder
#

that can also be swapped at runtime

acoustic belfry
#

oh!

acoustic belfry
#

nvm doesnt works either

rich adder
#

I mean it would work but you would probably make it feel nicer by smoothing out a speed value using a curve or some lerping

acoustic belfry
#

idk man, it just doesnt dash for now

#

i think the problem is something else

#

i dont know what

#

but something

#

or might be the return value?

rich adder
#

you haven't explained whats happening so i have no idea lol

acoustic belfry
#

doesnt move

#

just...walks

#

when the if is shaped like this

            if (dashTime <= 0)```
it works like a sprint

when is shaped like this
```        if (Input.GetKey(KeyCode.LeftShift) && valeriaMove != 0 && dashTime <= 0)
``` it doesnt dash
#

what im doing wrong?

rich adder
#

these are pretty much the same thing, though depends what other code you put outside the dashTime check

acoustic belfry
#

whole script

 {
     if (Input.GetKey("d") || Input.GetKey("right"))
     {
         valeriaMove = 1f;
     }
     else if (Input.GetKey("a") || Input.GetKey("left"))
     {
         valeriaMove = -1f;
     }
     else
     {
         valeriaMove = 0f;
     }
     dashTime = Mathf.Max(dashTime - Time.deltaTime, 0f);

     if (Input.GetKey(KeyCode.LeftShift) && valeriaMove != 0 && dashTime <= 0)
     {
             dashTime = dashCooldown;
             dashTimer = dashDuration;
             isDashing = true;
             spriteRenderer.color = Color.cyan;

             if (Input.GetKey("d") || Input.GetKey("right"))
             {
                 rb2D.linearVelocity = transform.right * dashSpeed;
             }
             else if (Input.GetKey("a") || Input.GetKey("left"))
             {
                 rb2D.linearVelocity = -transform.right * dashSpeed;
             }
             return;
     }
     else
     {
         rb2D.linearVelocity = new Vector2(valeriaMove * runSpeed, rb2D.linearVelocity.y);
     }
     if (isDashing)
 {
     dashTimer -= Time.deltaTime;
     if (dashTimer <= 0f)
     {
         spriteRenderer.color = Color.white;
         isDashing = false;
     }
 }```
rich adder
#

dash is a quick burst of speed, you're coding it like a sprint

acoustic belfry
#

when what i should do

rich adder
#

make a coroutine for it first of all so its not a crammed mess

rocky canyon
#

lerps are cool too.. or MoveTowards

acoustic belfry
#

i mean, how that would look like, idk im just trying to make it the simpliest posible for now, enchancement later

rocky canyon
#

MoveTowards for the value that is

acoustic belfry
#

how

rocky canyon
#

start it to at give it a burst of speed (maximum) and Movetowards it down to zero) that being the value being a added on ur rigidbodies vel

acoustic belfry
#

huh

rich adder
#

could also use AnimationCurve to switch up the easing / burst speeds

acoustic belfry
#

how that works

rocky canyon
#

finalVelocity = moveInput * runSpeed + dashVelocity;

#

then when u engage dash() dashVelocity = Mathf.MoveTowards(dashVelocity, 0, dashDecay * Time.deltaTime);

acoustic belfry
#

i got lost

rocky canyon
#

i sometimes call it 'damp'

#

okay... assume ur logic is.. (if were pressing wasd we just moving..

acoustic belfry
rocky canyon
#

basically.. itd be kinda doing the same thing.. dampening a value that ur using to be an extra force on ur rigidbody

#

the rigidbody movement still happening in the fixedupdate

#

it depends on what kinda dash u want..
if u do a coroutine u'd basically be turning isDashing boolean or something on.. then waiting and then turning it off

#

there would be two options here... 1 would be a dash that starts strong.. and then decays (a movetowards or lerp in a loop)

#

or.. it'd be a dash that just gives u extra power for a certain length of time

rich adder
# acoustic belfry how that works

Coroutine for running some code while an action is happening.. its just like another update loop basically or could be a fixed if yeilding fixedupdate

acoustic belfry
#

Huh? Idk i just want a simple dash i can understand, doesnt matter how it goes

I want it to quickly move to the key i pressed, like a lil push

#

Lil explosion

acoustic belfry
rocky canyon
#
IEnumerator Dash()
{
    isDashing = true;
    rb2D.velocity = new Vector2(facingDir * dashSpeed, 0);
    yield return new WaitForSeconds(dashDuration);
    isDashing = false;
}```
acoustic belfry
#

In theory

#

But at high speed and vert short

rocky canyon
#

this would be an example coroutine

acoustic belfry
#

So it looks like a dash

rich adder
#

Id use a while loop inside of it and do the burst in there with a curve modifying the speed

acoustic belfry
#

And without coroutines?

rocky canyon
#

void Update()
{
    if (Input.GetKeyDown(KeyCode.LeftShift) && dashVelocity == 0)
    {
        dashVelocity = dashStartSpeed;
    }
}

void FixedUpdate()
{
    // Regular move + dash push
    float move = Input.GetAxisRaw("Horizontal");
    float finalX = (move * runSpeed) + dashVelocity; // **note the + dashVelocity.. if its 0 then it doesnt affect ur speed.. but when u dash it starts strong.. and then lowers back to 0

    rb2D.velocity = new Vector2(finalX, rb2D.velocity.y);

    // Smoothly decay the dash velocity
    dashVelocity = Mathf.MoveTowards(dashVelocity, 0f, dashDecayRate * Time.fixedDeltaTime); // **because of this
}```
#

ofc with linearVelocity instead of velocity..

#

u could watch the additional dashVelocity starts at like 5... and then go down towards 0.. by w/e speed u want..

acoustic belfry
ivory bobcat
# acoustic belfry And without coroutines?

Without a coroutine, you'd have to manage your states to avoid operating certain lines codes during certain scenarios. If it's not too complicated, a timer or whatnot would suffice. Else, I pray for whoever has got to read the code in the far-near future UnityChanOops

acoustic belfry
#

Coroutines then

acoustic belfry
ivory bobcat
#

Starting and Stopping coroutines have some cost but likely it isn't going to be a game changer

acoustic belfry
#

Cost?

rocky canyon
#

for a coroutine ud also probably want to countdown a cooldown timer for the dash

#

so u cant accidently spam it

formal tide
#

I did research abt which method should i put my controls in. They say i should put input requests in update() and physics in fixedupdate() is it true? Or should i put every control inside update() and i didnt understand what if i dont use fixedUpdate for my controls. Its just WASD and Space to jump. Im just practicing.

ivory bobcat
#

Yeah, the initial cost but likely it'll not be your limiting factor

rocky canyon
#

you'll probably end up with many coroutines in ur game.

#

if ur doing sequential stuff based off of any kind of timer ull have to use one

#

unless ur a wizard coder and can do it some other way..

acoustic belfry
#

Oh, got it

#

Well. Thanks

ivory bobcat
formal tide
#

Im just trying to learn logic behind all of this

ivory bobcat
#

Some physics members can operate in regular Update like modifying the velocity property, adding force as impulse and whatnot but more often than not, Fixed Update is where physics operations that need to be synced should operate.

formal tide
#

I wrote everuthing inside fixedupdate now i need to seperate physics and input request.

rich adder
#

and you never use * Time.deltaTime inside addforce or .velocity

formal tide
rocky canyon
#

GetAxis or GetAxisRaw

#

and use those as multipliers

rich adder
rocky canyon
#

or if ur using new input^

#

but yea.. a composite input

formal tide
#

Im using new input system. Can i use getaxis

#

In it

rocky canyon
#

u can.. but u wouldnt want to

#

then ud have to be running both systems

#

use a 2d composite input

#

from the action map!*****

formal tide
#

Where is action map. Im beginner i dont know

rocky canyon
#

it looks like this in the project window

#

with w/e its named in urs or w/e u named it since u said ur using it

rocky canyon
#

^ bam

formal tide
#

Thanks

formal tide
#

for example it says it uses same approach for keyboard but i didnt understand it

#

how can i make it

rich adder
#

its literally explaining the same exact thing in your code Keyboard.current.spaceKey.

#

Keyboard is a an inputDevice it mentiones it there

shut swallow
#

This only happens when I introduced reloading within the game

cinder stump
shut swallow
north kiln
shut swallow
#

no, I do have a script that disable the player controller script, but it has no mentions of the input mapping

sour fulcrum
#
        public static void Add<T>(this T[] array, T value)
        {
            array = new List<T>(array) { value }.ToArray();
        }

can i do this or can i not reinitialize myself via extension like this

shut swallow
#

I coul pastebin rq if you wanna see the code

north kiln
#

You can fix this by just adding one questionmark anyway, it's so minor.

#

_inputActions?.Dispose();

shut swallow
#

player is enabled on start

north kiln
sour fulcrum
#

Yeah ok, no dice doing that neatly in a extension yeah? Worstcase can chuck it in my utils

north kiln
#

Just use ref

#

Looks like extension methods for classes don't support ref 🤔 I seem to be mistaken

shut swallow
# north kiln `_inputActions?.Dispose();`

thanks this did the trick
But I have another question, when I paused the game, I could not interact with the ui on the screen
Do I need to disable my current input mapping for the EventSystem to kick in?

#

Since EventSystem uses a different Input actions asset

north kiln
#

I don't believe so

shut swallow
#

I'm wondering if any scripts could make this a problem

north kiln
north kiln
sour fulcrum
#

Wait in the context of an extension?

#

w/o ref?

#

your righttttt just not easy for me to do that rn

#

lemme go do it

shut swallow
#

I've checked that I've toggled all raycasting on

north kiln
#

I think that's just all it shows with the input system annoyingly. I've absolutely no idea why

sour fulcrum
#

@north kiln nah must be same size

#

need resize w/ ref

#

oh well

#

ty for checking

shut swallow
#

how

#

oh nvm I solved it

#

this was blocking my ui elements

north kiln
#

Oh no, I'm mistaken, someone on my project just has a dumb API lol

#

their API doesn't resize the array at all 😆

sour fulcrum
#

i think i keep using a array indexof extension from a random unity input module lmao

#

we love random extensions

formal tide
#

Should i care abt efficent code even tho it works fine

cosmic dagger
#

Only when it becomes problematic where it effects the quality/performance of your game . . .

median hatch
#

its always fun when you come back to a script after 1 week and you dont remember anything you wrote

cobalt relic
#

hello, FACING CRASH ON ANDROID com.unity3d.player.UnityPlayerActivity.onCreate,
ANR ON ANDROID [libc.so] __futex_wait_ex
anyone have idea about these?

lime sigil
#

heyo
just joined for some more insight
i just started with unity but i have worked with c++/c#/python before for years

i was wondering, i'm am developing an app and for ease of maintainibility the ui is all in c# but still using uitoolkit, so i can avoid the string look-up part for elements which could easily become un-manageable since it's based on string ids

how could i approach mouse over events for elements like foldouts?
just looking for general guidance, since i'm not sure if i should go with a custom foldout class or there is a build in method that google didn't show

sharp solar
#

do i really have to check if key down every frame?

#

is there any signal based approach to inputs

wintry quarry
sharp solar
#

alright thank you ill look into it

formal tide
lime sigil
cobalt relic
# lime sigil heyo just joined for some more insight i just started with unity but i have work...

You're definitely on a smart path — keeping everything in C# for UI Toolkit is a great move for maintainability and avoiding messy string-based queries.

For mouse-over events like hover detection on elements such as Foldout, you can use the built-in UI Toolkit event system — specifically:

foldout.RegisterCallback<PointerEnterEvent>(evt => {
Debug.Log("Mouse entered");
});

foldout.RegisterCallback<PointerLeaveEvent>(evt => {
Debug.Log("Mouse left");
});
This works with any VisualElement, including Foldout. If you're planning to reuse this logic or apply custom behavior, creating a subclass like CustomFoldout or HoverableFoldout is totally valid and clean.

lime sigil
cobalt relic
# lime sigil oh thank you i didn't know ui toolkit had callbacks that's perfect, it's just th...

You're very welcome! Glad to hear it's working out for you so far and yep, callbacks in the UI toolkit can really streamline things early on. Refactoring into a custom class later sounds like a solid plan too once things get more complex.
And absolutely feel you on the HTML pain — string queries for UI elements can be a nightmare to maintain. You're definitely not alone there!
If you need help later when you start that refactor (or anything else), feel free to reach out. Good luck with the build! 🚀

lime sigil
#

yeah for now i'm doing on-the-fly prototyping, it's for a modeling software so starting now would be a pretty bad idea as much as using string queries for this
will reach out if i do thank youjunowaCorazoncito

deep moss
#

How do I toggle checklist tick when snapping object

shut swallow
ivory bobcat
shut swallow
#

I haven't made any modifications to the player script, but it still yielded the same error when i pressed restart

    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        Resume();
    }```
shut swallow
#

but normally when you exit to another scene you will destory all current GOs

ivory bobcat
#

What is a PlayerInputActions? The new Unity Input Actions?

shut swallow
#

it's not exactlt new anymore but yes it's the new input system

ivory bobcat
shut swallow
#

no, I just dispose it on destroy

#
    {
        _inputActions?.Dispose(); 
    }```
#

oh nvm i just disable it before disposing it and that seems to fix the issue
unity doesn't like it when I just straight up dispose it i assume

ivory bobcat
#

Could it perhaps, not have been destroyed because the reference was null?

shut swallow
#

I assume so yea, but wouldn't you always have a input system of some sort at play at any time?

ivory bobcat
#

The null conditional check would only hide the problem if you're actually not properly disposing of resources. The error seems to be informing you that you haven't disposed of the input actions.

sour fulcrum
#

out of curiousity, do you need to explicitly set _inputActions to null there or does the dispose do it cleanly (re: using the ?)

ivory bobcat
#

Is the variable being set to null somewhere?

sour fulcrum
#

Might be misunderstanding dispose in this context, if that's the case don't worry about that question 😄

shut swallow
ivory bobcat
#

Where do you assign _inputActions it's reference?

shut swallow
#

whenever you make the mapping, the script (and the class) is made

#

so there should only be one instance

acoustic belfry
shut swallow
#

since coroutines is async

hexed terrace
#

performance cost

sour fulcrum
ivory bobcat
shut swallow
#

ic

sour fulcrum
ivory bobcat
#

As long as they aren't starting thousands of coroutines per frame, they should be okay.

ivory bobcat
#

How are you assigning _inputActions it's value/reference, through the scene-inspector?

shut swallow
ivory bobcat
#

As is, I'm assuming it's null and _inputActions?.Dispose() gets ignored thus not throwing an NRE but still throwing a memory leak error.

ivory bobcat
shut swallow
#
    private CameraInput cameraInput;

    void Start()
    {
        playerCharacter.Initialize();
        playerCamera.Initialize(playerCharacter.GetCameraTarget());

        _inputActions = new PlayerInputActions();
        _inputActions.Enable();
    }```
ivory bobcat
#

Okay, so you've assigned it in Start

#

Are you assigning _inputActions a different value anywhere?

shut swallow
#

nope, not that I know of

ivory bobcat
#

Are you able to share the script so that we can check? !code

eternal falconBOT
shut swallow
ivory bobcat
#

If the script isn't being compiled because of compilation errors, you may be getting errors that aren't up-to-date.

shut swallow
#

I just noticed

#

did that made compilation fail?

ivory bobcat
#

Only you would know (visible console errors)

north kiln
#

No, empty statements are valid

shut swallow
#

doesn't pop up

#

I mean it did pop up a while ago but didn't seem to have trouble now

ivory bobcat
#

I'm not certain then as _inputActions is a private member and not re-assigning it's value anywhere other than in Start

#

Gameplay is referenced in Update but you aren't really doing anything dangerous with it that I'm aware of.

north kiln
#

I would breakpoint inside the Enabled function and make sure all the calls are coming from what you expect

open apex
#

Hi! I have been working on c# for a while. I am still a beginner, have learnt the basics but now want to switch to unity mobile game development. All tutorials I found are usually "this is how I did x,y,z" rather than "this x and this is how it works" and etc. They are not exactly helpful or teaching, is there any tutorials I could use to start off of?

#

Currently I am mainly lacking knowledge about mobile input

#

(FYI I finished the whole w3schools tutorials and did a few projects to properly learn and practice the skills)

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

fickle plume
acoustic belfry
#

how many people uses coroutines oftenly? idk, it is a good idea?

ivory bobcat
frosty hound
#

You've asked this question before for something else. Use a timer, not a coroutine, for things that are happening which can be interrupted or modified midway.

#

A dash is exactly something that can be interrupted or modified.

acoustic belfry
#

but i dont need it for the dash anymore

#

i need it for something else, to make the melee attack last longer than a click

frosty hound
#

[Whatever it is you're using it for] if it can be interrupted or modified in any way.

naive pawn
#

coroutines can be interrupted too

naive pawn
frosty hound
#

They're a hassle to maintain

naive pawn
#

use something that's readable and works, and hopefully generalizable

acoustic belfry
naive pawn
naive pawn
acoustic belfry
#

ok

naive pawn
#

you're in analysis paralysis

#

just pick one and go with it

acoustic belfry
naive pawn
#

in fact there isn't even really a clear line between coroutines and counting deltaTime lol

#

you can count deltaTime in a coroutine as well

acoustic belfry
#

huh

#

idk for now, i want it to make anything inside the overlapbox to get damaged more than one click

#

i mean, constantly?

ivory bobcat
# ivory bobcat Without a coroutine, you'd have to manage your states to avoid operating certain...

For minor stuff, I think if-statements are fine. I'm not too fond of coroutines as they seem a bit unnecessary but my nested timers and conditional branches with large compound conditions (states) quickly become ugly. The ease of helping folks on the Unity Discord platform without having to directly maintain (maintaining isn't a bad thing, if you've got the resolve and time) states has made me use coroutines often when helping others. Other than that, if the task is super simple a timer would be more than adequate. My opinion.

burnt vapor
#

@acoustic belfry
If you want my 2 cents, use timestamps with Timer.Time (the page has a good example). Works for plenty of logic and is very scalable for whatever you might want to hook onto it. I understand you want a dashing mechanic, so you could use an "Dash end timestamp" and from there your code can apply force and effects based on the time before the dash ends.

acoustic belfry
#

ooh seems interesting

idk i just need the AirSlash and DashSlash (preferible AirSlash) to wait a lil longer before dissapearing

  {
      machete_swingTimer = machete_swingSpeed;
      if (isDashing)
      {
          currentStyle = meeleStyle.DashSlash;
      }
      else if (!valeriaTocoPasto())
      {
          currentStyle = meeleStyle.AirSlash;
      }
      else
      {
          currentStyle = meeleStyle.Combo;
      }
      switch (currentStyle)
      {
          case meeleStyle.Combo:
              MeleeAttack(machetepos, attackRange, attackRange, meleeDamage);
              break;
          case meeleStyle.AirSlash:
              MeleeAttack(transform, attackRange, attackRange, meleeDamage + 2);
              break;
          case meeleStyle.DashSlash:
              MeleeAttack(transform, attackRange * 2, attackRange, meleeDamage + 3);
              if (valeriaMove != 0)
              {
                  rb2D.linearVelocity = new Vector2(valeriaMove * dashSpeed * 2f, 0f);
              }
              break;
      }
  }```
naive pawn
#

animation events are also a thing

acoustic belfry
#

my og structure idea was to burn them, until i realized that for each animation event i would need a function, wich would be...lame

acoustic belfry
naive pawn
#

probably with some manual checking but it'd be way harder

acoustic belfry
#

oof

acoustic belfry
naive pawn
#

an event to activate and an event to clean up

#

that's my setup

#

but whether that works for you depends on how you want it to work, which i have no idea of right now

acoustic belfry
naive pawn
#

no

#

that could be part of it, but that's not what i'm talking about

acoustic belfry
#

huh?

#

then how

#

a event calls a function

#

but what that function do?

naive pawn
#

whatever it needs to

#

there's a ton of ways to do this

#

you're asking like there's only one correct way lmao

#

this is something you need to design

sharp solar
#

when a function is called how can i make it so that something starts happening every frame

frosty hound
#

Set some bool value to true and check that in Update.

polar acorn
sharp solar
frosty hound
#

You would check 1 bool, each frame, for 10000 frames.

#

If you're implying that that's going to be a performance issue, it won't.

polar acorn
sharp solar
#

sorry ive not worded clearly what i mean

frosty hound
#

That too ^

#

Depends on what you mean by 10000 times.

sharp solar
#

my problem is checking every frame to do something instead of being able to schedule and deschedule it to happen every frame

#

no checks