#💻┃code-beginner

1 messages · Page 627 of 1

wintry quarry
#

Seems like you should probably take a slow read through the code and see if it makes any sense anymore

narrow pulsar
#

alr

wintry quarry
#

Anyway the SoundController.Jump thing would have to do with the SoundController script, not this one

nimble apex
#

the problem is , u can have local function, but u never make names thats related to monobehaviour

#

like i will never use Awake,Update,Start as my function name

sour fulcrum
#

no the issue is he has an update function in an update function

wintry quarry
#

this is clearly not an intentional local function though

#

this is some kind of copying error

nimble apex
#

sad

narrow pulsar
#

ill show it again this time

rich adder
teal viper
#

!code

eternal falconBOT
narrow pulsar
#

heres soundcontroller

rich adder
#

did you quick action a new jump method?

narrow pulsar
#

wait

#

wrong thing

#

let me redo it rq

polar acorn
narrow pulsar
#

im supposed to put jump into something like this

#

itl show a slot for me to insert the code and it detects if the player jumps with a vector thats on the player

#

so itl look like this

polar acorn
#

Okay, so... what calls jump()?

teal viper
#

The holy spirit

narrow pulsar
#

i have zero clue im lost in it myself

#

im frankensteining code together by the way

teal viper
#

Did you not write that code?

narrow pulsar
#

yeah no im trying to like mash 2 and 2 together and jump is the only thing thats missing

#

both examples work

teal viper
#

Make sure you understand the code before copying it into your project.

narrow pulsar
#

alright

#

sorry for confusing you guys

#

ill try to rewrite it from scratch so its less of a pain

#

to read

teal viper
#

That's not the problem. The problem is that you probably missed some important parts when copying the code. Make sure you understand how/where/when this code is called/executed from.

versed light
#

🥲 I'll try your code and see how I get on! Thanks

grand badger
#

more correct architecture should be something like: soundController.PlaySound(PlayerSounds.Jump);

narrow pulsar
#

thanks for the formatting tips

grand badger
#

not a formatting thing xD it's architecture -- has continuation on its way

narrow pulsar
#

arent they the same

#

or am i confusing terminology

grand badger
#

and SoundController should be kinda like:

public class PlayerSoundController : MonoBehaviour {
    [SerializeField] List<PlayerSoundPair> soundPairs;
    [SerializeField] AudioSource source;

    public void PlaySound(PlayerSounds soundToPlay) {
        var pair = soundPairs.Find(x => x.soundID == soundToPlay);
        source.clip = pair.clip;
        source.Play();
    }

    [System.Serializable]
    class PlayerSoundPair {
        public PlayerSounds soundID;
        public AudioClip clip;
    }
}

public enum PlayerSounds { Jump, Talk, GetHit, SwingSword, ShootBoomerang, .. }
#

(or even AudioSource.PlayOneShot(pair.clip) if you don't wanna make setups)

sour fulcrum
#

this is a little much for someone new

grand badger
#

I opt to disagree. I think this is EXACTLY what someone new should get into

sour fulcrum
#

you think someone who is a complete beginner should dive into non-behaviour classes and linq?

grand badger
#

[System.Serializable] classes configurable via the inspector definitely

#

Linq not so much but can't help it 😛 Also Find is not part of linq

grand badger
# narrow pulsar or am i confusing terminology

I think that's more likely. With a couple of sentences these are the high level differences:

  • Formatting is how your code looks spatially (like how many empty spaces/lines you have, etc)
  • Architecture is how your code is accessed (like which class accesses which, what methods it calls, etc)
narrow pulsar
#

ic

#

thanks 4 the clarification

#

i tend to know what im doing when it comes to reading code somewhat but actually knowing what to put and where is alot more annoying for me

#

i havent even scratched the surface of enums on the language i primarily use

grand badger
#

Yeah no rush. Unity has a nice learning curve but you gotta follow it yourself to climb it

#

that's because Unity allows you to pretty much brute-force your way through everything

#

like nothing stops you from adding a SoundManager with 1000 sound references and 1000 PlaySound methods, but that's not efficient when you wanna do it again

frigid sequoia
#

I kinda have a like a logic problem that I am not sure if I am gonna be able to express it properly... Let's see if someone could help.... I got all the entities stored on a singleton script with some lists. Now I want to give the entities a chance to be able to assign priority to these entities. Each entity having a reference to how much of a priority each entity is FOR THEM SPECIFICALLY. I was using dictionaries to have the entity as key and int as value inside the each entity, but I am now seeing that that might not be optimal? Cause one important thing is I don't want each different entity to have a priority value, but rather the TYPE of entity. Like for example, if the enemy is composed by 3 archers and 2 wolves; all archers would be priority 3 and all wolves would be like 8. I dunno, maybe I am superoverthinking this

#

It's mostly cause maybe having a list of all entities and them a dictionary that basically copies the list and add to it a value is kinda.... redundant??

#

What makes more sense to me is for the dictionary to store the reference of how much priority THE TYPE of enemy is worth rather than every single entity, but not really sure how to do that....

timber tide
#

So every archer instance will have its own priority value? Keep it local to that instance then

#

Unless you need to order the priorities so quickly look them up, then keep a sorted list on a manager

#

Oh read over that. If it's by a instance type, then it should be on the SO of that instance type then, and similarly same idea with the sorted list

frigid sequoia
#

This is the script I am using for like basically all entity/characters as a base. The name would be basically the type. So the player is meant to give commands to a bunch of player characters and I want for example one of them to have all enemies with the name as "archer" for example as priority 3. All archers would be stored on the list that holds all entities, but I find kinda unnecessary to duplicate data on the dictionary of aggro script when all entities of the same type are gonna share a value

timber tide
#

Yeah, keep it on the SO, unless you mean to change that priority at runtime, then you need some dictionary where key is the enemy instance type and value is the priority

#

or make a bidirectional dictionary and make one where priority is the key ;p (assuming priority values are unique)

frigid sequoia
#

Well, the idea is the player will have to assign to her character what are they meant to be focusing, FOR EACH

timber tide
#

so what's the idea, you get into range of a bunch of enemies and want to find the greatest priority threat?

frigid sequoia
#

So maybe rogue has archers at priority 3, but maybe a mage has them as 8. They are not meant to be changed once the combat has started, but all those things have to be modified on runtime on a UI menu

timber tide
#

so grab all the enemies in range, run through each of their SOs (or check the manager dictionaries if the priority changes at runtime) and then resolve it

frigid sequoia
timber tide
#

Yeah, it's just a bunch of iterating and then caching the highest/lowest values as you go through every enemy

#

then once you're done you have your final value or values you can work with to find that answer

frigid sequoia
#

Yeah, it's just very abstract cause I am still not sure how I even want the UI to look like

#

But the idea is: Scene has 2-3 enemy types. Prebattle you assign what logic your dudes are gonna follow and the priority order of the enemy types. Then they act without your control

#

You can assign it to all characters, to ranged/melee, tank/healer/dps or specific to that one character and they would follow whatever command is the most specific

#

So that's A LOT of steps

#

Not sure how to handle it

teal viper
frigid sequoia
#

I guess I could, the type being a string

#

I also need them to do the same for allies though, that being slightly different cause in that case it would indeed need to hold them all, since they are all meant to be distinct, even if they are both the same class

teal viper
#

Why string?

#

Are these not separate classes?

#

If they are the same class, how do you make a distinction between them?

frigid sequoia
#

They are all GeneralBehaviurManagers

#

Then they have stuff that tells them apart

#

On that same script they do have a name to tell them apart

#

Then they all also have a AbilityManager, which is a superclass where you would use more specific stuff, like a rogue has a specific AbilityManager to use abilities from a rogue

#

But for enemies, the basic ones pretty much just attack automatically, so they do not really need one

#

So I cannot really tell them apart for a type of script if that's what you mean

sour fulcrum
#

where is the sprite for the character icon defined?

frigid sequoia
sour fulcrum
#

Might make more sense to pull some of that info into some shared scriptableobject that you could also use to reference rather than a type

#

(think that's what Mao was suggesting initially)

frigid sequoia
#

So what would be the difference between referencing a string and SO WITH a string + a bunch of other info I don't really need?

eternal needle
solar totem
#

getting an error every time i run my code "Please open a folder with a solution to debug"

grand badger
#

I'd run an antivirus scan

grand badger
frigid sequoia
#

Yeah, I am like pretty convinced doing all this heavy ordering each frame on several different entities is not a great idea....

timber tide
#

Unless you've thousands it's not the biggest problem. Throw it in fixed update though cause no reason you do need to do it based on framerate, or make your own cooldown timer

bright zodiac
#

also not following prev convs above

normal turret
#

Hey guys, what's up...? I just have a quick question about Parallax Scrolling

#

I followed a video guide on YouTube by Dani and the Parallax Scrolling works perfectly fine

#

But for some reason...when I try to adjust my character's Z-index, the entire background moves with my character

#

The code works fine, it's just I'm having layering problems...

timber tide
#

Well, you have the background child* to your character, so they offset relative to them

#

Something that isn't parented respects the world space such that z+ forward x+ right, but when you child a transform then its parent that determines the space that it behaves in.

#

And meaning that this parent is now considered the vector.zero of that space relative to the child

normal turret
#

Ok nice thank you, I'll double check the hierarchy

#

That does make sense though, I just have to seperate the background and my character into different nodes...

twin sky
#

!docs

eternal falconBOT
twin sky
#

do you guys have a tutorial on animator ? i'm trying to animate a character in 2D, and to call animation left / right when i press D or A but it can't seem to work somehow

normal turret
#

My character is in the default sorting layer, and my character is seperate from my Camera, where my background is a child of that node (Morning Background)

#

Sid Marhsall is my main character, but somehow I think I did something that connected the background

#

One of the background layers is animated...does that affect anything...?

timber tide
#

Ah, sorry had mistaken background checker as background

normal turret
#

No you're good...the layering is confusing me, for some reason

timber tide
#

Well, what I see on your scene too is that you're using cinemachine. Take a look at your camera coordinates and move your character, does the camera now update coordinates?

#

Because if your camera is moving, then so are those backgrounds. I assume this is part of the tutorial though which is why it's set up like that

normal turret
#

Yes I think the coordinates update as I move my character

#

But for some reason when I move my character the entire background moves with it

timber tide
#

Any reason you're moving the character on the z anyway?

normal turret
#

Eh I thought maybe I could put my character all the way in the front on the same Z-index as the tilesets...

timber tide
#

Would layering/sort groups not solve all that? Usually that's recommended over z-sort

normal turret
#

So I should make some sorting layers and group all the layers into those layers...?

#

Or I guess can I just use Order in Layer...?

timber tide
#

Yeah the order on layer stuff. Otherwise you need to tell cinemachine to not follow your character's z coordinates which I'm not too sure how to go about that, but there's probably a way though not a module I play with too much.

normal turret
#

Ok nice that might be easier, I'm going to see if that works, thank you

#

It seems like everything else is fine except for the part where the background moves with my character...

#

Even though the character and backgrounds aren't parent/child of each other

timber tide
#

Yeah, but the camera is moving on the z, which is moving those backgrounds ;p

normal turret
#

Oh ok that makes sense...then I have to figure out the Cinemachine...

timber tide
#

There's probably some z constraint property if you can find one

normal turret
#

Oh nice, to lock the camera on a specific Z-layer...?

#

Yeah that's a good idea, I'll see if I can find one if I can, thank you I appreciate you

timber tide
normal turret
#

Nice thank you, I'll try it out. Hopefully it works, never knew that something as simple as layers can be complicated (well...at least for me)

umbral bough
#

Hi, I am working with the Timeline.
I would like to change the properties of an Audio Track via script but can't figure out how to access its properties.
They appear in the inspector, as can be seen in the first screenshot, but I can't get them via script.

umbral bough
# umbral bough Hi, I am working with the Timeline. I would like to change the properties of an ...

I managed to find this on some random post on forums:

audioTrack.CreateCurves("nameOfAnimationClip");
audioTrack.curves.SetCurve(string.Empty, typeof(AudioTrack), "volume", AnimationCurve.Linear(0,0,1,1));
audioTrack.curves.SetCurve(string.Empty, typeof(AudioTrack), "stereoPan", AnimationCurve.Linear(0,-1,1,1));
audioTrack.curves.SetCurve(string.Empty, typeof(AudioTrack), "spatialBlend", AnimationCurve.Linear(0,0,1,1));

But I can't figure out why the first line is needed, or whether it's even correct in the first place, and also, do I need to call that first line every time I wanna change the values or what?
This has to be some of the weirdest, most undocumented api I've ever seen, makes 0 sense why it's not built in...

hexed terrace
#

They won't even add an event for when the timeline has reached the end (finished or looped)

grand snow
#

there is something for reaching the end but it doesnt work properly

#

With unitask i had to do a wait until for the time reaching very close to the end

shy edge
#
using UnityEngine;

public class PlayerCamera : MonoBehaviour
{
    public float sensX;
    public float sensY;

    public Transform orientation;

    float xRotation;
    float yRotation;

     private void Start(){
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
     }

     private void Update(){
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

        yRotation += mouseX;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90, 90f);

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.rotation = Quaternion.Euler(0, yRotation, 0);
     }
}
#

ok idk why it looks so weird but anyone know why my camera starts by looking down at the ground when i press play?

#

all rotations in unity are set to 0

verbal dome
#

^That probably amplifies your problem because the game lags when you start it up and you get a large delta time

shy edge
#

thanks

shy edge
#
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Movement")]
    public float moveSpeed;

    public float groundDrag;

    public float jumpForce;
    public float jumpCooldown;
    public float airMultiplier;
    bool readyToJump;

    [Header("Keybindsa")]
    public KeyCode jumpKey = KeyCode.Space;

    [Header("Ground Check")]
    public float playerHeight;
    public LayerMask whatIsGround;
    bool grounded;

    public Transform orientation;
    
    float horizontalInput;
    float verticalInput;

    Vector3 moveDirection;

    Rigidbody rb;

    private void Start(){
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

    private void Update(){
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
        MyInput();
        SpeedControl();
        if(grounded){
            rb.linearDamping = groundDrag;
        }
        else{
            rb.linearDamping = 0;
        }
    }

    private void FixedUpdate(){
        MovePlayer();
    }

    private void MyInput(){
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");
#

        //when to jump
        if(Input.GetKey(jumpKey) && readyToJump && grounded){
            readyToJump = false;

            Jump();

            Invoke(nameof(ResetJump), jumpCooldown);
        }
    }

    private void MovePlayer(){
        //calculate move direction
        moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
        if(grounded){
            rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
        }
        else if(!grounded){
            rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
        }
    }

    private void SpeedControl(){
        Vector3 flatVel = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);

        //limits velocity if needed
        if(flatVel.magnitude > moveSpeed){
            Vector3 limitedVel = flatVel.normalized * moveSpeed;
            rb.linearVelocity = new Vector3(limitedVel.x, rb.linearVelocity.y, limitedVel.z);
        }
    }

    private void Jump(){
        // reset y velocity
        rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

        rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
    }

    private void ResetJump(){
        readyToJump = true;
    }
}
#

when i press space it wont jump

#

yes my ground has the layer attached

verbal dome
#

And make sure that jumpKey is actually set to Space in the inspector

shy edge
#

and yes its set to space in the inspector

pseudo pagoda
#

is this a code problem cuz my invisible barrier aint working

verbal dome
shy edge
#

do i just set the bool to true by default?

eternal falconBOT
verbal dome
#

If it's true by default then the only downside is that you can jump at the start of the game if you start in the air

pseudo pagoda
#

i need to set the mc to is trigger as for the dialogue

shy edge
verbal dome
#

But you only invoke it when you jump

#

And you can never jump

shy edge
#

oh alr

#

no clue why gravity is being wonky

#

wait holon

#

lemme turn it to a mp4

frank flare
#

How can I change color v with the script?

#

I want the coin to blink before it despawns

slender nymph
twin sky
#
using UnityEngine;

public class npc_movement : MonoBehaviour
{
    Animator anim;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            anim.SetBool("walkleft", true);
            Debug.Log("WalkLeft");
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            anim.SetBool("walkright", true);
            Debug.Log("WalkRight");
        }
    }
}```

i got this very basic script, could someone tell me why my Booleans in my animator won't change please ? I've been struggling for hours now
slender nymph
#

make sure the animator parameters names are spelled correctly (and there's no extra whitespace in their names in the animator). also do the logs print?

twin sky
slender nymph
#

click them to edit them and make sure there is no extra whitespace

twin sky
#

CTRL + A

slender nymph
#

then congratulations! the animator parameters are being set by that code

verbal dome
#

How do you know they are not changing?

#

Make sure you have the animated object selected when looking at the animator in playmode

twin sky
verbal dome
#

You need to select an object so it knows which animator to draw in the animator window

#

If you have nothing selected then you just see the default values

tribal wave
#

can someone point me in the direction for a channel that helps with unity not unity scripting?

slender nymph
raw fiber
#

guys im trying to make a button for mobile game and it says it needs canvas i dont understand canvas can someone explaine me please

tribal wave
#

oh oops didnt see that

slender nymph
twin sky
slender nymph
#

then the issue is likely in your animator setup

twin sky
#

is the structure wrong ?

slender nymph
#

check the transitions

twin sky
verbal dome
#

You don't have a transition from idle to anything

#

The transitions are one-directional as you can see from the arrows

#

Ah you haver Any staate

twin sky
#

basically the entry is connected to the idle, and the any state is getting the "backright" or "fromright" depending if walkleft ou walkright is true

#

and when walkleft or walkright is false, then it comeback to idle position

verbal dome
#

Also your transition duration is 1.5 seconds?

twin sky
#

i feel very weird about using the animator feature

#

i might have situated the problem, in the screen i have my GameObject "NPC" and in it a GameObject called "state" the npc is the hitbox and the script is connected to this, so i have to click on "npc" to get, but the animations aren't showing because the animator is connected to "state"

#

so if i'm not wrong i should just move the script to state and not NPC

raw fiber
#

guys how do i make the vector3 movement again?

slender nymph
#

what do you mean by "the vector3 movement"

raw fiber
#

with the implemented axis from unity

slender nymph
#

and have you bothered going through the beginner pathways on the unity learn site like you've been advised?

slender nymph
twin sky
#

thanks @slender nymph & @verbal dome for the help mate, made me find my mistakes

polar acorn
raw fiber
#

when i try to open the animator only animation is opening why is it like that i want animator not animation

polar acorn
#

Then you should open the Animator window, not the Animation window

cunning rapids
#

Guys this may be a dumb question but why do I have to make both floats static if I want to reference it in a Vector?

private static float x;
private static float y;

private Vector2 someVector = new Vector2(x, y);
slender nymph
#

you cannot use non-static fields inside of a field initializer. if you want to use the value of the fields then construct the vector3 in a method using those fields

verbal dome
#

When initializing a field you cant use values from other member fields

#

With member i mean non static

#

Not sure if static fields are called members

#

I guess they are

cunning rapids
tight fossil
#

does a stack of several else if statements stops reading each one if one is true?

verbal dome
#

Yes

tight fossil
#

oh good

#

thanks :>

#

and i assume it goes down the list in order?

hexed terrace
#

yes, obvs

tight fossil
#

figured

hexed terrace
#

code generally runs from left to right, top to bottom

spiral oracle
#

what does it do essentially?

gaunt cipher
# spiral oracle what does it do essentially?

gets the X and Y of your canvas instead of using numbers which could be anywhere. You coded it as -611, and then you see buttons off screen, well that's -611. There can be a lot of difference between absolute position in editor and what the resulting pixel ends up being

gaunt cipher
#

float scaledStartX = 194 * _rectTransform.lossyScale.x;
float scaledStartY = 634 * _rectTransform.lossyScale.y;

This is an example from my own code but my UI graphic starts at 194,634 so I use this and then it works regardless of what you scale the canvas to

spiral oracle
#

ok so lossyY is the Y center and lossyX is the X center

#

according to what you said and the code you provided me

#

ok thanks for clarifying

gaunt cipher
#

np

raw fiber
#

hey guys uhm im programming with cours rn from unity and we are programming space invaders. We programmed the movement the animation everything but with the movement i got the problem that my charecter is moveing a little bit further when i stop pressing the button how can i fix that

slender nymph
#

sounds like you're using GetAxis rather than GetAxisRaw. GetAxis applies input smoothing which would cause that gradual slowdown after releasing the key

raw fiber
#

thanls

viral stag
#

Hi how do i get help in this server please is there a certain chat?

burnt vapor
viral stag
#

Ok thank you

rare elm
#

i bought a game kit and an art set, expecting to use them together. the problem is, the kit wants Sprites, and the art set is Tiles. Is there a way to make a sprite out of tiles, or do I actually have to go manually materialize these tile layouts to individual images?

#

i thought full rect / tiled was what i wanted but possibly not

slender nymph
#

not a code question, and tiles are made from sprites, so just use the sprites?

rare elm
#

well that's what i'm trying to do, but, when i set the sprite to the relevant sprite sheet, set the width and height as appropriate, set it to tiled, set it to full rect, i get the upper left hand corner six times

#

sorry, it's 2 tiles wide by 3 high, is where that number comes from

worthy tundra
#

i have a problem with the editor what channel should i ask in

slender nymph
worthy tundra
slender nymph
#

if only there were a channel specifically for when there are no other channels that your question relates to

slender nymph
rancid tinsel
#

why is this code not running? i thought as long as i pass the parameters into the coroutine before calling Destroy on the object, it will still work since its separate from the object?

#

the first debug goes through, and then its not instantiating anything or logging that application is quitting

slender nymph
#

is it this object that is being destroyed? because if so, then naturally any coroutines started on this object will not continue running

rancid tinsel
#

idk why

#

i thought coroutines were completely separate once theyre running

slender nymph
#

that is specifically how it does work. Coroutines are tied to the lifetime of the object that starts them, that is why disabling a gameobject also stops its coroutines

rancid tinsel
#

had no idea, thanks!

#

that will be the issue then

surreal minnow
#

I am raycasting from the camera and I want to apply a spread to it but my current method spreads in a square pattern instead of a circular one. Does anyone know how do it instead?

Vector3 direction = currentCamera.transform.forward;

Vector3 right = currentCamera.transform.right;
Vector3 up = currentCamera.transform.up;

Quaternion spreadX = Quaternion.AngleAxis(UnityEngine.Random.Range(-currentAngle, currentAngle), up);
Quaternion spreadY = Quaternion.AngleAxis(UnityEngine.Random.Range(-currentAngle, currentAngle), right);

Vector3 spreadDirection = spreadX * spreadY * direction;
queen adder
#

I'm trying to use the object a script is being applied to as a variable in a function within the script, assuming i would use the this variable, but that hasnt worked and im not sure what the correct method is. Tried searching it up, but just got stuff about people asking how to use stuff from other scripts in a script 😭

slender nymph
#

be more specific about what you are trying to accomplish

#

because this refers to this instance of this object, in other words, if will refer to the instance of your component so if there is something else you are trying to get, you need to be specific

verbal dome
#

The forward angle should be 0...360 (or -180...180)

queen adder
# slender nymph be more specific about what you are trying to accomplish

ive got a function that finds the closest object to the object the script is on, from a list of objects. For the function to work, I need to pass the object the script is on, as a game object, and also the list of objects. I can pass the list of objects but idk what to use to pass the object the script is on, and assumed it was this but apparently not

slender nymph
#

correct, this would not be appropriate to pass there because it does not refer to a gameObject, it refers to this instance of this component. have you tried looking at the MonoBehaviour documentation to see if there is a useful property you could use?

verbal dome
#

@surreal minnow Oh and try both ways when combining the quaternions, i forget which one should come first

queen adder
#

found the answer, turns out its just gameObject which in hindsight shouldve been obvious

shadow maple
#

heya! i'm new here so please correct me if this isn't the right channel. 🙏 i'm having a really hard getting this to work for my college assignment. I have 3 scenes, 1 for gameplay, 1 for Win and another for game over. the game over screen has TMP Text with the button component with it, that triggers LoadGame() in the Level script.

however, when the game over screen is loaded, it keeps telling me that Level is inactive, where in reality it isn't. i tried doing a DontDestroyOnLoad to no avail.

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

public class Player : MonoBehaviour
{
    private GameSession gameSession;
    private AudioSource audio;
    private Animator animator;
    private SpriteRenderer spriterenderer;
    private Level level;
    public Transform spriteTransform;
    public int health = 20;
    public bool frozen;
    public bool isDead;
    [SerializeField] List<AudioClip> sounds = new List<AudioClip>();

    void Start()
    {
        gameSession = FindObjectOfType<GameSession>();
        level = FindObjectOfType<Level>();

        animator = GetComponent<Animator>();
        audio = GetComponent<AudioSource>();
        spriterenderer = GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        if (frozen)
        {
            return;
        }
        else
        {
            float delta = Input.GetAxis("Horizontal") * Time.deltaTime * 5;
            transform.position = new Vector2(transform.position.x + delta, transform.position.y);

            animator.SetFloat("Speed", Mathf.Abs(delta));

            if (delta != 0 && spriteTransform != null)
            {
                Vector3 newScale = spriteTransform.localScale;
                newScale.x = Mathf.Abs(newScale.x) * (delta > 0 ? 1 : -1);
                spriteTransform.localScale = newScale;
            }
        }

        KeepPlayerInView();
    }

    void KeepPlayerInView()
    {
        Camera viewport = Camera.main;
        Vector2 minBounds = viewport.ViewportToWorldPoint(new Vector2(0.1f, 0));
        Vector2 maxBounds = viewport.ViewportToWorldPoint(new Vector2(0.9f, 0));

        transform.position = new Vector2(
            Mathf.Clamp(transform.position.x, minBounds.x, maxBounds.x),
            Mathf.Clamp(transform.position.y, minBounds.y, 0)
        );
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Collectable"))
        {
            audio.PlayOneShot(sounds[0]);
            gameSession.AddScore(10);
        }
        else if (collision.CompareTag("Obstacle"))
        {
            if (health > 1)
            {
                audio.PlayOneShot(sounds[1]);
                health--;
                StartCoroutine(DamageColor());
            }
            else
            {
                health--;
                frozen = true;
                isDead = true;
                GetComponent<Collider2D>().enabled = false;
                GameObject.Find("GameCanvas").gameObject.SetActive(false);
                level.LoadGameOver();
            }
        }
        Destroy(collision.gameObject);
    }

    IEnumerator DamageColor()
    {
        spriterenderer.color = new Color32(255, 100, 100, 255);
        yield return new WaitForSeconds(0.25f);
        spriterenderer.color = new Color32(255, 255, 255, 255);
    }

    public List<AudioClip> GetSounds()
    {
        return sounds;
    }

    public int GetHealth()
    {
        return health;
    }
}
ivory bobcat
#

You've got an error

shadow maple
#

that's the one i was referring to, couldn't start because it was inactive. sorry i thought it got captured!

ivory bobcat
#

When an error occurs you can expect things to not work properly

shadow maple
shadow maple
ivory bobcat
#

Check the details pane and see where the error is occurring

rich adder
polar acorn
shadow maple
#
    public void LoadGame()
    {
        StartCoroutine(GameplayScene());
    }

it leads me to this

which the GameplayScene coroutine is:

    IEnumerator GameplayScene()
    {
        fader = FindObjectOfType<Fader>();
        fader.GetCanvas().GetComponent<Canvas>().sortingOrder = 1000;
        music.Stop();
        music.PlayOneShot(restartGameSound);
        fader.Transition("Black", "Out", 1f);
        yield return new WaitForSeconds(2f);
        SceneManager.LoadScene("Gameplay");
        FindObjectOfType<GameSession>().ResetGameSession();
        fader.Transition("Black", "In", 1f);
    }
shadow maple
polar acorn
shadow maple
#

LoadGame is called by the 'try again' button (a TMP text with a button component)

ivory bobcat
#

The error suggests that when you attempted to start the coroutine, the object was (still?) inactive. Have you set the object active/inactive anywhere?

polar acorn
shadow maple
#

no i haven't. I even tried before switching the scenes to "re-activate" the script to no avail (essentially setting it to active again)

shadow maple
rich adder
#

might be trying to run as the gameobject is being destroyed/disabled for scene switch

shadow maple
#

but why would it be destroying if I did a DontDestroyOnLoad prior?

rich adder
#

on Level not Player.cs no?

shadow maple
#

yee

polar acorn
# shadow maple sure thing!

First off - probably don't set it to "Editor", this should be runtime only.
Second, did you drag in the Level object from the scene into that box?

#

Or did you drag in a prefab

sharp abyss
#

can someone take a look

shadow maple
rich adder
#

are you running the script in the player prefab maybe ?

polar acorn
#

the prefab that doesn't exist

#

Which is why it says it doesn't exist

shadow maple
#

uhh no Level is only in the Level object

shadow maple
polar acorn
#

not the one in the scene

#

Those are two different Level objects

#

One that exists, and one that does not

shadow maple
#

huh okay.. i've been instructed that way so i guess that really didn't cross my mind 😅

let me give it a shot

polar acorn
#

The button calls the function on the object you drag in

#

If you drag in a prefab, it's gonna run the function on the prefab

#

So find whoever told you that you needed to drag in a prefab and slap em at least twice

shadow maple
#

i don't think i would want to do that to my lecturer but i'll definitely keep that in mind haha

polar acorn
#

They're getting paid for this? Three slaps.

shadow maple
#

okay! it's no longer erroring but now it doesn't seem to be doing anything...?

#

i'll try a quick debug.log

#

nada. no errors but it's not doing anything

polar acorn
shadow maple
#

in a way yes but it's not performing anything inside the Coroutine

#

not even a Debug.Log

#

i do appreciate y'all taking me a step closer though, thanks :)

humble forum
#
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    public TextMeshProUGUI scoreText;
    private float score = 0f;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
            return;
        }
    }

    void Update()
    {
        score += Time.deltaTime * 10;
        if (scoreText != null)
        {
            scoreText.text = "Score: " + Mathf.FloorToInt(score);
        }
    }

    public int GetScore()
    {
        return Mathf.FloorToInt(score);
    }

    public void ResetGame()
    {
        score = 0f;
        Time.timeScale = 1;
        SceneManager.LoadScene("Play Game"); 
    }
}
polar acorn
shadow maple
#

OH i found the culprit I think..

rich adder
shadow maple
#

my function inside the button got unassigned. let me try testing the game as a whole now

humble forum
#

public void RestartGame()
{
GameManager.Instance.ResetGame();
}
}

#

this mb

rich adder
shadow maple
humble forum
polar acorn
rich adder
# humble forum

ok so where is the script, you still didnt show it in the scene.
this cropped photo doesnt help

shadow maple
#

Level is on DDOL (assuming Dont Destroy On Load?), which does include the Level script that it's trying to access

rich adder
#

where is it

polar acorn
shadow maple
#

No i'm starting from Gameplay (different to what i've shown from the 'try again' screen) which then switches over to Gameover

polar acorn
#

I assume that Level is a singleton then, and it does something to destroy extra copies of it as you load a new scene, right?

humble forum
#

score += Time.deltaTime * 10;
if (scoreText != null)
{
scoreText.text = "Score: " + Mathf.FloorToInt(score);
}

shadow maple
#

Yes let me find the quick snippet..

humble forum
#

only on this

shadow maple
#
    void SetupSingleton()
    {
        if (FindObjectsOfType<Level>().Length == 1)
        {
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
polar acorn
rich adder
polar acorn
#

so it no longer exists

rich adder
humble forum
polar acorn
rich adder
shadow maple
#

Or do i just remove that code fully?

humble forum
humble forum
polar acorn
rich adder
#

I dont see GameManager

polar acorn
rich adder
#

where GameManager component..

humble forum
polar acorn
rich adder
humble forum
#
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    public TextMeshProUGUI scoreText;
    private float score = 0f;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
            return;
        }
    }

    void Update()
    {
        score += Time.deltaTime * 10;
        if (scoreText != null)
        {
            scoreText.text = "Score: " + Mathf.FloorToInt(score);
        }
    }

    public int GetScore()
    {
        return Mathf.FloorToInt(score);
    }

    public void ResetGame()
    {
        score = 0f;
        Time.timeScale = 1;
        SceneManager.LoadScene("Play Game"); 
    }
}
shadow maple
humble forum
rich adder
#

showing this script is useless

#

WHERE in the SCENE is this

#

Which Gameobject is it on?

polar acorn
humble forum
#

here

rich adder
#

TF

#

lol

polar acorn
humble forum
rich adder
humble forum
rich adder
#

and its still not fucking there

#

jesus

humble forum
polar acorn
# humble forum

Okay so when you said this was the object the game manager component was on you just straight up fuckin lied?

rich adder
polar acorn
#

We can't really do much to help if you're blatantly lying

rich adder
#

the SCRIPT on the GAMEOBJECT

#

the component

#

idk how else I should explain it

#

I dont see GameManager placed on any GameObjects..

polar acorn
humble forum
polar acorn
rich adder
#

if its none, why are you surpised the Instance is null

polar acorn
#

What fuckin game manager are you trying to reference then

humble forum
#

it just needs to call it from another script?

polar acorn
rich adder
#

you want to access a component thats not even in the scene..

polar acorn
#

there is none

#

it doesn't exist

rich adder
#

this what happens when you randomly paste scripts without any idea what they do...

polar acorn
#

you can't call functions on the concept of nothingness

humble forum
rich adder
#

Components go on gameobjects to do anything

polar acorn
humble forum
rich adder
#

are you though

polar acorn
#

If you want something to do a thing, and that something does not exist, it can't do the thing

rich adder
#

we had this problem last time

#

you have to know what a component is by now..

#

what you need for a component to do anything

#

also references are not a unity problem..

humble forum
rich adder
humble forum
rich adder
#

stop saying UE5

#

we're in unity now

#

all that is irrelevant

#

Unity works on Components, they need to be on gameobjects to exist

polar acorn
humble forum
#

wait the pic was useful already have it

polar acorn
#

If you do not have a game manager, then you cannot run code from a game manager

humble forum
polar acorn
rich adder
polar acorn
humble forum
rich adder
humble forum
polar acorn
rich adder
humble forum
#

im hella confused

rich adder
#

if its not carrying over then you never ran this scene prior to endScreen scene

polar acorn
# humble forum im hella confused

At the time you are getting the error, while the game is running, is there an object in the scene with the GameManager component on it

#

We keep asking questions, getting outright lies as answers, and have no way to know they are lies, so we start answering assuming you've told us what the actual state of the scene is, and since you lied on the first answer you have no idea what we're talking about

humble forum
#

guess i will look into it tommorow almost midnight now

rich adder
#

you just skipped into another thing until you get stuck then come here rather than learning the reasons behind the issue

shadow maple
rich adder
#

btw , use links for large !code blocks

eternal falconBOT
shadow maple
#

made it a link

polar acorn
shadow maple
#

which would be the Level instance?

polar acorn
#

The first one that ever exists when you start the game

shadow maple
#

OH okay I thought it was when a scene changed

sand mesa
#

how do you compared 2 euler angels?

ripe shard
sand mesa
#

or compare a euler angle to a float

#

something along the lines of this

ripe shard
sand mesa
#

right

ripe shard
#

you may want to convert that transform rotation to angle-axis representation

sand mesa
#

how?

#

cause Im comparing only transform.eulerAngles

polar acorn
#

Which angle do you want to compare to 210

shadow maple
#

oh my goodness after hours of working endlessly, thanks digi i figured that out at last

polar acorn
#

Remember to pay forward those slaps

sand mesa
polar acorn
# sand mesa

Checking if a vector is "greater" than another one doesn't really make sense

sand mesa
#

im trying to cook up a range

#

not a single correct value

ripe shard
#

maybe you actually dont even want to use angles

#

if this is about a clock, you could calculate the angle between the noon direction and the direction the hand is pointing in: Vector3.SignedAngle(noon, hand) > 150f

rich adder
# sand mesa

this would've made sense at very least could've compared magnitudes.

sand mesa
#

magnitudes?

#

Explain

rich adder
# sand mesa magnitudes?

dw about that now, magnitude would've just given you a single number that can actually be compared with > < not saying its correct but vector3 > vector3 doesnt make sense

#

if this is a clock you should only be using Z angle anyway no? why compare the entire V3

shadow maple
#

okkk i spoke too soon. 🥲

https://paste.mod.gg/lqwiaxwvmwhq/0

if i die once, everything goes well. gameover works fine, all dandy. buut when it comes to Debug.Log("Found"); in the GameObject.Find("TryAgain"){}, it prints TWICE and doesn't apply the level instance to the button.

#

-# i am slowly getting a headache. it's past midnight and i need sleep but i'm not going to rest well knowing that i still am having issues

sand mesa
#

It returns a value between -1 and 1

#

And the value is mirrored, so it doesn't work

rich adder
sand mesa
#

I had a debug log running transform.rotation.z

#

It was -1 to 1

polar acorn
polar acorn
#

that's rotation

rich adder
polar acorn
#

which is not in degrees

sand mesa
#

What do you mean it's a quaternion?!

polar acorn
#

because that's what it is

rich adder
#

max value is 1

sand mesa
#

I thought if I just ran transform.rotation.z, then Id get z, not a quaternion

polar acorn
#

rotation is a four-dimensional normalized complex vector

rich adder
#

not euler angles

polar acorn
#

If you want the eulerAngles, use eulerAngles

#

you've been using them in the code you've shown

rich adder
#

Quaternion doesnt use angles , would defeat the point of unity using it to store rotations

polar acorn
#

so you already know that

shadow maple
sand mesa
#

I was trying to measure rotation

#

Fine

shadow maple
sand mesa
#

If transform.rotation.z doesn't get me z as in -180 to 180

#

What does?

polar acorn
rich adder
polar acorn
#

I've mentioned it like twelve fucking times

sand mesa
#

I thought they were different entities!

polar acorn
polar acorn
polar acorn
shadow maple
#

i'll give it a shot tomorrow then, i'm having a hard time concentrating. thanks again for the help, i will note it :)

scarlet skiff
#

can someone tell me why no matter what sprite i drag into the sprite section of this image component the sprite wont change? these inventory slots have a prefab and once the game starts it spawns them in and u can scroll to change the sprite from a slot to a selected slot but when i manuall try to change it in the editor it wont change, what could possibly be the cause?

teal viper
scarlet skiff
scarlet skiff
rich adder
polar acorn
rich adder
#

things like OnValidate etc

scarlet skiff
#

oh i see, do they come from packages u downlaod or?

teal viper
scarlet skiff
scarlet skiff
scarlet skiff
teal viper
#

So far I don't see any issues in your screenshots. The image seems to render the sprite that is assigned to it. Does it not let you assign a different sprite or something?

scarlet skiff
teal viper
grand snow
scarlet skiff
#

it changes it back to what it was, but that is cuz of the script that should only run when the game is active, why does it not change when the game isnt active is what im wondering

grand snow
#

what calls this? does it check Application.IsPlaying ?

scarlet skiff
grand snow
#

i dunno what this component is but why are you doing GetComponent soo often when you can serialize vars and get once

scarlet skiff
scarlet skiff
grand snow
#

oh this is paused in play mode?

#

Id recommend making scripts for each component of the UI, e.g. "InventoryBar" and "InventorySlot" to better manage functionality and state

scarlet skiff
grand snow
#

im in the mentality of do it the non shit way that you can maintain in future

scarlet skiff
grand snow
#

its either in edit mode (not playing), play mode or play mode paused.

scarlet skiff
hidden fossil
#

where do i go if i want to learn how to like implement a wave structure

#

im a beginner scripter

scarlet skiff
grand snow
#

i see no good reason to figure this out then

teal viper
scarlet skiff
# grand snow i see no good reason to figure this out then

well, i was trying to add code that changes the slot sprite depending on its positioning (far left, far right, middle ones) and the script didnt change anything and i was wondering why, so my first though to debug this was to try to manually set a sprite and see what happens so i think figuring this out would help me find the root cause

grand snow
#

but setting a sprite manually doesnt really help you. It should be simple to do anyway. index 0 gets far left, index count - 1 gets far right, rest get middle sprite.

#

presuming your list of slots is sorted correctly (and having 1 list of inventory slot components greatly helps with preventing mistakes with something like this)

scarlet skiff
#

so index of far right changes

grand snow
#

thats fine, easy to spawn a new slot and insert at the end

#

or you insert 1 before to avoid needing to auto do this bg changing

scarlet skiff
grand snow
#

you have options but id try to improve the design and if there are issues in normal use then hopefully you can correct em.
If i was to do this id either have 3 prefabs (2 variants) to have the alt designs for the start and end, or set the bgs from the managing script when the inv size changes.

scarlet skiff
#

it really was that simple appearantly, still dont get why i cant change it when the game is paused but i guess it doesnt matter now

scarlet skiff
spiral oracle
#
using TMPro;
using UnityEngine;

public class Actions : MonoBehaviour
{
    public GameObject actionButton;
    public GameObject actionHierarchy;
    public TextMeshProUGUI DialogText;
    public float TextWriteSpeedDelay = 1;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        AddActionButton(3);
        WriteDialog("hiiiiii, I'm literally John Pork and I'm edging my mogging streak rn.");

    }

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

    }

    public void AddActionButton(int numberOfButtons)
    {
        if (numberOfButtons > 4)
        {
            numberOfButtons = 4;
        }

        int buttonY = 330;
        int[] buttonX = new int[4];
        buttonX[0] = 276;
        buttonX[1] = 718;
        buttonX[2] = 1170;
        buttonX[3] = 1636;



        for (int i = 0; i < numberOfButtons; i++)
        {
            GameObject newActionButton = Instantiate(actionButton);
            newActionButton.transform.position = new Vector2(buttonX[i], buttonY);
            newActionButton.transform.SetParent(actionHierarchy.transform, true);

        }
    }

    public void WriteDialog(string message)
    {
        Console.WriteLine(message);
        DialogText.text = "";
        float timer = 0f;

        for (int i = 0; i > message.Length; i++)
        {

            if (timer >= TextWriteSpeedDelay)
            {
                DialogText.text += "" + message[i];
                timer = 0f;
            }
            else
            {
                timer += Time.deltaTime;
            }
        }
    }

    

}```

I'm wondering how I'd go about doing this, because it doesn't work
I'm trying to make text progressively appear in a dialog box, but nothing shows up at all.
#

only look at the last function and start()

#

the rest doesn't matter to what I need help with

ancient stirrup
#

make a coroutine instead

spiral oracle
#

I'll google it

#

oh ok

#

I'll look into doing that

#

oh my god it's so simple

sour fulcrum
#

❤️

spiral oracle
#

ok it works

native thorn
#

I apply 0 motor torque to my wheel colliders but they don't stop for a good 1-2 seconds, any clue?

#

Oh my god I'm an idiot

#

A motor torque of 0 is just an energy of 0

#

Not that it moves at 0....

dusky pike
#

public class OverlayManager : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private AreaOverlayManager _areaOverlayManager;
    private GameObject _pressedObject;
    private bool _isHolding;

    public DeckManager deckManager;
    public DiscardManager discardManager;
    
    private bool _isAreaOverlayOpen = false;
    private bool _isOverlayOpen = false;

    private void Awake()
    {
        _areaOverlayManager = GetComponent<AreaOverlayManager>();
    }
    
    public void OnPointerDown(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            _pressedObject = gameObject;
            _isHolding = true;
            
            if (!_isOverlayOpen)
            {
                StartCoroutine(HoldCheck());
            }
        }
    }
    
    public void OnPointerUp(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            if (_isOverlayOpen)
            {
                CardOverlayManager.Instance.CloseOverlay();
                _isOverlayOpen = false;
                return;
            }


            if (_isAreaOverlayOpen && !gameObject.CompareTag("Card"))
            {
                _areaOverlayManager.CloseDeckOverlay();
                _isAreaOverlayOpen = false;
                return;
            }
            
            if (_isHolding)
            {
                _isHolding = false;
                if (_pressedObject == gameObject)
                {
                    OpenOverlay();
                }
            }
        }
    }
#

    private IEnumerator HoldCheck()
    {
        yield return new WaitForSeconds(1f);
        _isHolding = false;
        _pressedObject = null;
    }

    private void OpenOverlay()
    {
        switch (gameObject.tag)
        {
            case "Card":
                CardOverlayManager.Instance.OpenOverlay(gameObject);
                _isOverlayOpen = true;
                break;
            case "Deck":
                _areaOverlayManager.OpenDeckOverlay(deckManager.GetContent());
                _isAreaOverlayOpen = true;
                break;
        }
    }
#

I have this really simple Code snipet

#

For some reason.... _isOverlayOpen gets changed to false

#

I basicly want to press Right Click on an Object and open an Overlay that shows the Card

#

and when i press right click again i want it to close the overlay

#

There are some special cases when a DeckOverlay is open but that doesnt matter rn cause im fully focussed on the "Card" Tag

#

When i click again the Overlay doesnt close

#

I tested a bunch of stuff, including setting _isOverlayOpen public

#

My log basicly tells me, that it gets changed to true and after a single frame it gets changed to false

#

I honestly dont understand the problem at all

timber tide
#

I'm not sure if that's a good way to go about checking if the player has held the pointer down over a duration. I'd just make a timer and place it in update to check if the player has held long enough when the pointer is pressed down, otherwise stop the timer and reset it to 0.

#

Otherwise you would probably want to cancel the coroutine if they do remove that input.

celest jay
#

why does this debug.log look like this? [Worker]

#

is this thing new?

verbal dome
#

Looks like it is being called from a worker thread, not the main thread

#

Did you put that in a constructor or something?

celest jay
#

[CreateAssetMenu(menuName = "Item/Item")]
public class ItemSO : ScriptableObject
{
    [ShowSprite] public Sprite sprite;
    public string ItemName;

    /// <summary>
    /// Used by the Crafting System
    /// </summary>
    [Tooltip("Used by the Crafting System")] 
    public int id = 0;

#if UNITY_EDITOR
    void OnEnable()
    {
        FixAllID();
        Debug.Log("OOsOO", this);
    }```
#

seems like it's getting called by all of my item each time an item is made

timber tide
#

interesting. Didn't know the directives for the editor worked on another thread

verbal dome
celest jay
#

just duplicate

verbal dome
#

Oh in the editor

celest jay
#

oh yes

verbal dome
#

Does that class have the ExecuteAlways/ExecuteInEditMode attribute?

celest jay
#

it's not

timber tide
#

What's the method?

celest jay
#

I'm just not sure why it keeps spamming Awake and onenables

timber tide
#

If it's an editor only method, then that makes more sense

celest jay
#

I want something that will only happen automatically when I duplicated this SO

verbal dome
#

What does FixAllID do?

timber tide
#

You probably want to be using instantiate or create instance then if this isn't for editor purposes

verbal dome
#

I mean I get what you're trying to do but does FixAllID use Resources.Load or something?

#

OnEnable gets called when the SO is loaded into memory for the first time

celest jay
#

I just want to make sure no item have same id, but OnValidate is trash

timber tide
#

Ah, ok I see. Use the ISerliazation instead then

#

OnValidate falls into similar editor problems with SOs

verbal dome
#

Check every other asset for duplicate ids when it gets serialized/deserialized?

timber tide
#

It should be called when it's duplicated I believe

#

and similar to OnValidate, it will invoke when you do make edits

celest jay
#

it's just as spammy as OnValidate

timber tide
#

I mean, OnEnable should work fine here though if it's a one-time operation

#

just next time you load the editor it'll do it again ;p

celest jay
#

OnEnable keeps getting called on all Items everytime im making a new item

verbal dome
#

That's why Im asking what happens in that FixAllID method

celest jay
#

that's why it was using the other threads lol

#

    public void FixAllID()
    {
        existingIDs = new();
        RepeatingID = new();
        foreach (string sss in AssetDatabase.FindAssets("t:ItemSO"))
        {
            ItemSO asset = AssetDatabase.LoadAssetAtPath<ItemSO>(AssetDatabase.GUIDToAssetPath(sss));
            if (asset != null)
            {
                if(existingIDs.Contains(asset.id))
                {
                    RepeatingID.Add(asset);
                }
                existingIDs.Add(asset.id);
            }

            int newID = existingIDs.Max();
            foreach(var item in RepeatingID)
            {
                while(existingIDs.Contains(newID))
                {
                    newID++;
                }
                item.id = newID;
                newID++;
            }
        }
        existingIDs = null;
        RepeatingID = null;
    }```
#

oh

verbal dome
#

So yeah you are loading all of them again

celest jay
#

it's getting loaded

#

ye I just saw it

#

I'll just use resources then

timber tide
#

Could always just flag the asset to not run the logic, even if it gets loaded ;p

celest jay
#

it's inside the folder anyways

verbal dome
#

So you need some kinda flag like Mao suggested

timber tide
#

Otherwise make a constructor that you call when you duplicate it

#

and set the ID once and forget the unity methods

verbal dome
#

They are duplicating it in the editor

#

Right?

celest jay
#

yes

rugged beacon
#

why this this awake() not running, help im tilted

rich adder
#

You have your Debugs hidden/collapsed

rugged beacon
#

oh

#

any idea why my other script .onEnable run before the awake ?

rich adder
rugged beacon
#

dang

#

!code

eternal falconBOT
rugged beacon
#
    private void Start()
    {
        InputManager.Instance.playerInput.Ingame.Togglemap.performed += Toggle;
        InputManager.Instance.playerInput.Ingame.Togglemap.Enable();

    }

    private void OnDisable()
    {
        InputManager.Instance.playerInput.Ingame.Togglemap.performed -= Toggle;
        InputManager.Instance.playerInput.Ingame.Togglemap.Disable();

    }

hope using start() instead of onenable() doesnt break the input system

rich adder
#

the only issue without using OnEnable though if you disable this and re-enable the inputs will stop working

rugged beacon
#

idk imo this wouldnt but all tutorial would recommend using onenable to register the input.enble and disable() vice versa

rich adder
rugged beacon
#

i could yea, but that would mean all other input script would need tinkering
what about this lol:


    private void Start()
    {
        OnEnable();
    }

    private void OnEnable()
    {
        InputManager.Instance.playerInput.Ingame.Togglemap.performed += Toggle;
        InputManager.Instance.playerInput.Ingame.Togglemap.Enable();
    }

    private void OnDisable()
    {
        InputManager.Instance.playerInput.Ingame.Togglemap.performed -= Toggle;
        InputManager.Instance.playerInput.Ingame.Togglemap.Disable();

#

the start for that singleton inputmanager instantiated first

#

enable and disable for the UI gameobject enable/disable

rich adder
#

you mean manually enabling the gameobject? not sure I understand

#

I would just fix the input manager exec order

#

managers should setup their singleton before all other scripts should sub their events anyway

rugged beacon
#

ah yea move the singleton before default time

rich adder
#

yeah after all those are managers / special cases (singletons)

#

you wouldn't touch others

rugged beacon
#

my ass was thinking moving all the input scripts

rich adder
#

yeah that would be bad.
a few scripts that usually in charge of initializing others is reasonable

rugged beacon
#

anw thanks gamer

sour fulcrum
#

VS is giving me the green squiggly so i wanted to vibe check, Is this kind of partial implementation/backporting of an abstract generic function allowed?

public abstract class BaseClass
{
    public abstract void PartialGeneric<T>(T content) where T : MonoBehaviour;
}

public class DerivedGenericClass<T> : BaseClass where T : MonoBehaviour
{
    public override void PartialGeneric<T>(T content)
    {

    }
}
#

(but removing this means it fails to match the function 1:1 and screams)

#

(i think the answer is no)

bitter spruce
#

anyone knows why this is happening 😢

#

im in the prefab itself

#

i cant edit my collider

#

it randomly appeared back nevermind

polar acorn
#

Looks like it happens when you have multiple inspectors open. Maybe the "Scene" tab and the "Prefab" tab count as separate inspectors?

pure drift
#

i have this soundtester script in my game attached to a gameobject but whenever i run my game the checkmark goes away which means my audio doesnt work does anybody know why this would happen

ruby zephyr
#

Hey guys, since
!leearn have coding tutorials on it and it doesn't explain well how the codes work, let's say I wanna learn how those lines of codes work by researching, what and where should I do the research?

north kiln
#

By having a generic function inside of a generic class you're doing this:

public class DerivedGenericClass<T0> where T0 : MonoBehaviour
{
    public void PartialGeneric<T1>(T1 content) where T1 : MonoBehaviour
    {
    }
}```
ruby zephyr
ruby zephyr
sour fulcrum
ivory bobcat
ruby zephyr
hollow gazelle
#

So guys... Where and how do you recommend to learn c#?

Im looking to create a platformer, and developing enemy AI... To detect holes and jump across them, if target goes to higher grounds then follow player trails and jump to get to higher grounds (like breadcrumbs), and adding waypoints to the map so that the enemy when there's no target they randomly move though neighbors waypoints through the map.

mortal flint
#

I have a newb question about resizing the box for a TextMeshPro. I think I may be close, but searching hasn't given me a straight answer if I'm on the right track. I have a TextMeshPro that I have set to my default size. I want to be able to make it wider or smaller based on some code. Really all I want to change is the width by a scale to be a multiple of the default.

Based on the UI, I guessed that I need to grab the **RectTransform **- rt = Text.gameObject.GetComponent<RectTransform>(); -, then would I use rt.rect.width to get the current width?

After that, how do I correctly set the new width? **SetSizeWithCurrentAnchors ** looks promising. Can I just use rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, originalWidth * scale)?

eternal needle
tranquil forge
lone tundra
#

I have an issue with debug.log where it would output two variables. One of the variables is equal to the other variable. However, they report different values.

#

boardTileName is a string. Can anyone help?

wintry quarry
lone tundra
wintry quarry
#

Also boardTileName is clearly an int not a string

wintry quarry
#

Or at least an array of ints

lone tundra
#

boardTileName is a string

wintry quarry
#

I see you're looking at one character from a string

#

why are you looking at a single character from the string?

#

What's with all the magic numbers here? This code is sketchy

#

What are you trying to do

#

Anyway the int is 48 because 48 is the ASCII code for the 0 character

lone tundra
#

boardTile is a gameObject array which contains tiles in the format "x, y". I'm iterating through a part of the array to add into another array.

wintry quarry
lone tundra
wintry quarry
wintry quarry
lone tundra
#

it shows what the values go into

wintry quarry
#

This code is atrocious. If you want to get the number from the string you need to parse it

lone tundra
#

how do i parse it?

wintry quarry
#

Simply casting it to an int gets you the ASCII code

wintry quarry
#

Directly

west radish
#

!ide

eternal falconBOT
sour fulcrum
#

does anyone have a fancy linq way to check if two lists are holding the exact same contents

#

was expecting google to give me some perfect function but getting a lot of varying more handcrafted solutions

void thicket
#

SequenceEqual

sour fulcrum
#

😲

topaz mortar
#

How does SceneManager.GetActiveScene work when I have multiple scenes loaded?

charred spoke
#

I suppose ActiveScene is misleading, it is not just a scene that is loaded and enabled but rather the “main scene” where new game objects get created and the lighting and occlusion settings come from. There can only be one active scene at a time

topaz mortar
#

I would be loading several scenes to move my player through them without any loading screens

charred spoke
#

Either the first one that loaded or what ever scene you set as the active one

#

You can also manually set the active scene if needed

vestal anvil
#

so ive been using godot before and now i switched here cause it supports C# better but is there like a unity version to the godot event system where you can use a master object with all the methods and then just connect them to the system? cause it kinda feels unoptimized to add the script to the object and then reference that same object in the event trigger,i want a single object to hold all the methods and reference that object to the event trigger of others all in the same scene

#

kinda hard to explain since each engine handles events very differently

sour fulcrum
#

might help to provide an example

topaz mortar
#

Does Unity have a build in way to reference scenes in the inspector? Or do I need to use strings?

teal viper
charred spoke
topaz mortar
#

yeah I've seen that, so there's no built in way?

charred spoke
#

No but just use this package

topaz mortar
#

I just need the scene names, not sure if this library will be compatible with my game (using fishnet)

charred spoke
#

Has nothing to do with fishnet

#

It’s just a way to serialize a scene asset in the inspector

vestal anvil
# sour fulcrum might help to provide an example

this is on godot,the blue arrow is where the script is,there are like 3 methods for each button you see,the yellow shows the event and that event is just attached to that master script,in unity i usually just add the script to the button and reference the button inside an event trigger

charred spoke
#

Under the hood it’s the same you can use build index or name or what ever

teal viper
vestal anvil
#

cause in unity i have to reference the same button inside the event trigger

#

i tried referencing another object but my methods dont show up

#

i dont want to create 1000 new scripts for each button that has only a single method,that would get very cramped and confusing fast

#

actually i dont really need to make more scripts but i would still need to add the script to the object

#

essentially i just dont want every object to have a script

teal viper
#

Do they have parameters?

vestal anvil
#

they are public but for script instances im not sure? how do i reference script instances?

#

also no they dont have parameters

teal viper
#

Were you assigning the script asset or something?

vestal anvil
#

Oh then yeah I did that

#

No,I didn't even know you could do that until a min ago when I tried lol

teal viper
#

Script assets are just text files. They are not related to the actual script instances.

grand snow
#

the unity event ui isnt that difficult to use... drag in the object, select the component and function

#

or sub in code, do whatever

teal viper
vestal anvil
#

So I just have to get used to the different way I assign events

teal viper
#

There are many differences. Might want to go over the beginner pathways on unity !learn to make sure you're not misunderstanding something based on a different engine.

eternal falconBOT
#

:teacher: Unity Learn ↗

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

vestal anvil
grand snow
#

Even though unity could make it work with private functions, they chose not to which was wise. If you want a private function to work then subscribe in code:

[SerializeField]
Button button;

//Somewhere
button.onClick.AddListener(MyPrivateFunction);
median hatch
#

unity is pretty versatile when it comes to creating your own systems

median hatch
#

took me an hour to figure this one out...

grand snow
#

well yea they are separate, one is pre configured to be done via reflection, one is a delegate subbed in code

vestal anvil
median hatch
#

unity is more like a sandbox game (minecraft)

vestal anvil
#

also i have another question,can i check for 2 events of the event trigger? i have a menu which makes each button turn red when hovered or selected thru navigation keys and i ran into a glitch where if you hover a button and then use directional keys then the previous button stays red and i wanted to check for the Select and PointerEnter events so the method wont run twice

grand snow
#

easy, pointer enter -> set "hover" to true, pointer exit -> set "hover" to false. Check bool when select is invoked.

vestal anvil
#

oh yeah i guess that would work

#

my first idea was to make the entire event trigger inside the code and make an if statement but this seems much easier with the same effect

grand snow
#

ui buttons already have functionality for changing stuff when hover or selection state changes though.
You can do whatever in code though, events just report that a thing happened or changed so you can do what you want after.

#

you can also receive the events in monobehaviours directly without a event trigger:

public class MyMono : MonoBehaviour, IPointerClickHandler
{
  public void OnPointerClick(PointerEventData eventData)
  {
    Debug.Log("I was clicked!", this);
  }
}
vestal anvil
#

oh damn thats very cool

#

godot had something similar but never used cause they use a very bad camel case naming convention which made me go insane

twin sky
#

hey i've been struggling a lot using animator, is there a documentation somewhere because i've been looking but can't manage to documentate myself, thanks

twin sky
#

thanks mate

raw fiber
#

hi im making a space invaders rip-off from a udemy unity cours and it spawns these bullets but its not spawning infinit bullets it only spawn 4 what is the problem

#

thats the code

polar acorn
# raw fiber

Does this object ever get destroyed or deactivated

wintry quarry
raw fiber
#

there are no errors

wintry quarry
#

Where did you look?

raw fiber
#

ahh wait

wintry quarry
#

My guess is that you are instantiating an object in the scene instead of a prefab

#

And your object in the scene is being destroyed

#

Hence the error

#

Fix it by using a prefab instead

raw fiber
#

whats the problem i followed the cours

wintry quarry
#

You messed up

#

You didn't use a prefab

raw fiber
#

im using a prefab

wintry quarry
#

No you're not

#

You assigned the field to an object in the scene

#

Assign it to the prefab

#

Drag the prefab from your project window into the slot in the inspector

raw fiber
#

um using it like in the tut

wintry quarry
#

Doesn't seem like it based on your error

raw fiber
wintry quarry
#

Again, drag the prefab from the _project window _ into the bullet slot of the inspector of the spawner.

wintry quarry
#

BulletPlayer is an object in the scene

#

Delete it from the scene

#

Instead you must drag the PREFAB into the slot

raw fiber
wintry quarry
#

The prefab is in the project window not in the scene

#

None of the bullets should be in the scene at all

#

Delete them from the scene

#

They should only be in the project window/assets folder

raw fiber
#

the guy from the cours said it like that

wintry quarry
#

Doubtful

#

But regardless

#

It's wrong

#

Are you here for advice or to stick to what isn't working?

#

You also need to look at your full error message and make sure you're even looking at the right script

polar acorn
raw fiber
#

now nothing works

polar acorn
raw fiber
#

what is the problem now can you @wintry quarry please explain it again to me would be very nice

polar acorn
#

You say what problem is, we say why problem is

astral falcon
#

Maybe not beginner

mystic wasp
#

Im currently working on a 2D roguelike, and made a prototype for handling active-use items - but before I move on, I wanna check if there's a more efficient way to go about this

I basically made an Item class, and from there I made a TNTItem script so I could make a scriptable object and use that? But it seems off because this would gradually be cluttered

polar acorn
mystic wasp
#

How do I go about that? I think I know what you mean, but I was confused since I have the use item functionality in the TNT class/script so I wasn't sure where to put it

wintry quarry
# raw fiber now nothing works

"Now nothing works" is meaningless. Explain what's happening, what errors you're getting and how you have set things up now.

#

I explained above what you should be doing.

polar acorn
# mystic wasp How do I go about that? I think I know what you mean, but I was confused since I...

You'd need to write the item script as generic as possible, so that it can handle all of the functionality of the TNT object. For the most part, you want your ScriptableObjects to do as little as possible, and serve as containers of data. You might want whatever thing uses these SOs handle the differences. At some point, there will be a MonoBehaviour referencing the SO, so you can have that behaviour be the one that handles deciding whether the item explodes or not.

If your SO is for something like an inventory, you don't actually need functionality, just a name, icon, stack size, etc. that all items will share, and maybe a prefab that it spawns when you use it in the world. You'd have the TNT object spawn in that TNT prefab, and that handles the exploding.

mystic wasp
#

Alright, got it

#

ty!

celest holly
#

Hi, my smooth brush wont change size, any fix?

raw fiber
#

what does that mean now?

celest holly
#

you havent set the bullet as any gameobject or such

cosmic dagger
# raw fiber

It means exactly what it says. The error states that you have not assigned the variable named bullet on the SpawnBulletController script, and that you should probably assign it . . .

raw fiber
#

its assinged

polar acorn
# raw fiber what does that mean now?

It means the variable bullet of SpawnBulletController has not been assigned. You probably need to assign the bullet variable of the SpawnBulletController script in the inspector.

cosmic dagger
raw fiber
#

what do you mean?

#

sorry im new to unity and scripting

polar acorn
cosmic dagger
# raw fiber what do you mean?

You have to place the script on a GameObject. Check if you have more than one of those scripts on a GameObject in your scene . . .

raw fiber
#

fixied it guys thanks it was assinged to my 2 enemys

#

like i sayedd im new

#

xdd

green copper
#

when using 2D objects, how is it handled which objects can interact with eachother?

Like, if I place a gameobject with a sprite and 2d collider at 0 10 0 with a rotation of 0 0 0, will it be affected by another one at 0 9 0 with the same rotation if i'm trying to create a parralax effect by using the different positions?

#

or will they be handled independently as different physical "layers?"

cosmic dagger
raw fiber
#

i like this sever

cosmic dagger
#

You can setup your collision matrix to determine which layers interact or ignore each other . . .

green copper
polar acorn
# raw fiber like i sayedd im new

You've learned a valuable lesson: Errors never lie. If it ever seems like an error is telling you to do something you already did, you gotta really think about what assumptions you've made that were wrong because it's definitely the human's fault in those cases. In this situation it was the assumption that the error was about the one that did have the assignment, and that you didn't have any extra copies.

Programs are very precise, notice it didn't say all SpawnBulletControllers were broken, just that a SpawnBulletController was. Keep this in mind for future errors

cosmic dagger
#

This will determine which sprite(s) display in front of or behind another . . .

dusky pike
#
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

public class OverlayManager : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private CardOverlayManager _cardOverlayManager;
    
    [Header("Rechtsklick Handler")] 
    private GameObject _pressedObject;

    [Header("Managers")]
    public DeckManager deckManager;
    public DiscardManager discardManager;

    private bool _isOverlayOpen = false;

    private void Awake()
    {
        _cardOverlayManager = GetComponent<CardOverlayManager>();
    }
    
    public void OnPointerDown(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            Debug.LogWarning("Rechtsklick gedrückt!"+ _isOverlayOpen.GetHashCode());
            
            _pressedObject = gameObject;
        }
    }
    
    public void OnPointerUp(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            if (_isAreaOverlayOpen && !gameObject.CompareTag("Card"))
            {
                _areaOverlayManager.CloseDeckOverlay();
                _isAreaOverlayOpen = false;
                return;
            }
            
            if (_pressedObject == gameObject)
            {
                OpenOverlay();
            }
        }
    }

    private void OpenOverlay()
    {
        switch (gameObject.tag)
        {
            case "Card":
                CardOverlayManager.Instance.OpenOverlay(gameObject);
                _isOverlayOpen = true;
                Debug.LogWarning("Öffne das KartenOverlay Und änder Zustand zu true!" + _isOverlayOpen.GetHashCode());
                Debug.Break();
                break;
            default:
                Debug.Log("Kein bekanntes Overlay vorhanden");
                break;
        }
    }

My Private bool: "_isOverlayOpen" gets changed to false after a single frame

keen owl
#

Is your conditional being met?

#

And !code please

eternal falconBOT
dusky pike
polar acorn
dusky pike
#

i get false

#

    public void OnPointerUp(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            
            Debug.LogWarning("Rechtsklick losgelassen"+ _isOverlayOpen);
        
            if (_isOverlayOpen)
            {
                Debug.LogWarning("Schließe Overlay! Und änder Zustand zu false!"+ _isOverlayOpen.GetHashCode());
                _cardOverlayManager.CloseOverlay();
                _isOverlayOpen = false;
                return;
            }

polar acorn
dusky pike
#

what i expect: First click on a "Card" Tagged Object:

  • Open an Overlay/set "_isOverlayOpen" gets set to true
  • Second Click close the overlay > because _isOverlayOpen is true
dusky pike
#

The Code gets set to true but its instanly false again

I tried calling it with an Update

#

An got a single "true"

keen owl
#

You can create a separate method that only changes the boolean value when you click on a card and test that

polar acorn
eternal falconBOT
keen owl
#

If it still persists, something else is changing it outside that script

dusky pike
keen owl
#

Oh you’re right, I didn’t catch that

#

But you can still try explicitly changing it though just as a test

polar acorn
polar acorn
# dusky pike yes

Looks like the only things that ever set _isOverlayOpen to false are when this object is created, and when you right click. If you're not right clicking, you're probably getting logs from two different OverlayManagers, one where it's true, and one where it's false

dusky pike
#

But how would i test if i had multiple Scripts with the same name open?

polar acorn
#

Search for them in the hierarchy during play mode

#

t: OverlayManager in the search bar on the hierarchy

dusky pike
#

Jesus Christ😂

#

That seemed to be part of the Problem, i accidently attached it to my card prefab...

But im pretty sure there is still something wrong with the bool, gimme a min

#

I think im beginning to Understand my Problem

#

The OverlayManager never worked to begin with

raw fiber
#

can someone explain me // new

verbal dome
raw fiber
#

yes just explain what it does and why its there

verbal dome
#

Why it's where? Show context

#

Usually it is used with a constructor to create a new instance of an object

#

Like a struct or a class

slender nymph
raw fiber
#

im doing a cours rn but i dont understand it realy

verbal dome
#

You're not supposed to take your first learning steps on this server

slender nymph
raw fiber
#

i understand im just askin for it what is your fcking problem bro im just asking what it means because i understand it better from a person that speaks to me then a person that is doing a video

slender nymph
#

you've been doing this for days where you just want "this one thing explained" instead of going and actually learning everything as a cohesive unit. since you refuse to actually learn the basics i'm just going to block you, and don't be surprised when others do the same

raw fiber
#

im learning rn and im nearly finished with my first game but i dont understand the meaning of new

#

ive written so many lines of code

slender nymph
#

again, this is because you have skipped learning the actual fundamentals of the language you are using. just because you've copied a bunch of code from tutorials does not mean you've actually learned anything. this is clearly demonstrated by your constant need for explanations of absolutely basic concepts

raw fiber
#

no

verbal dome
#

new is one of the basic concepts for sure

raw fiber
#

look at that it german because im german dont look at 3 thats all stuff i already know like how to open inspector and stuff but look at all other they are all finished

slender nymph
#

clearly that is either a bad course that doesn't actually teach all of the basics or you didn't pay attention to it.
as i've pointed out there are beginner c# courses pinned in this channel, including ones that can be easily translated to german (specifically the microsoft ones can be set to german) and actually teach you the important topics you need to understand

raw fiber
#

its not finishednotlikethis

#

im not at the end of the course

slender nymph
#

but you've completed the C# Basics section

#

so my point stands

raw fiber
#

thats are just the lections that i have

#

"BASICS"

raw fiber
slender nymph
#

i don't give a shit that i piss you off a bit, because all i've done is give advice that you should take because you are trying to get ahead of yourself. you currently do not have the skillset required to understand all of what you are doing and you are instead making other people supplement that for you instead of just learning the basics so that you understand it yourself instead of needing to come in here to ask about basic stuff 5 times a day

raw fiber
#

ok if you think your so smart give me the course you used to learn c# and we will see if i get so "GOOD" like you

#

and if my question pisses you off then just dont watch them and ignore it

slender nymph
#

if only i had mentioned multiple times where you can find beginner c# courses that cover the absolute basics that you need to know

raw fiber
#

where? send me a link

slender nymph
#

the last one is even from three days ago

raw fiber
#

ok i will start with beginner scripting

slender nymph
#

start with intro to c# since you clearly want to learn in a language other than english. because that is the microsoft course that can actually have its language changed properly

raw fiber
#

im sorry for insulting you

tawny grove
#

why is this never reaching pass the 'wait until', even when jumping becomes false?

#

i am running it in a coruntine btw

rocky canyon
#

do u call StopCoroutine() anywhere when jump becomes false?

tawny grove
#

i do not

#

i did not know that existed let me look into that

rocky canyon
#

u could try it w/ a regular while loop

tawny grove
#

i feel like that would cause alot of lag no?

tawny grove
#

waituntil triggers

#

rest of function

rocky canyon
#

yield return null is basically the same as WaitUntil performance-wise i believe..
and while will check each frame..

tawny grove
#

alright, ill test it out, ty

rocky canyon
#
while (jumping)
    {
        Debug.Log("Inside while loop, jumping = " + jumping + ", frame: " + Time.frameCount);
        yield return null;
    }```
#

just to compare it to ur yield return new WaitUntil(() => jumping == false);

tawny grove
#

this is what i tried but am still having issues

#

and im very confused by this, why is jumping considered false out of the loop but true inside? (the "false" print is from the point where the function is called, and will only run the function if jumping is false)

slender nymph
#

keep in mind that the yield is only evaluated at a specific part of the frame, if the bool is not false at that part of the frame then nothing about the coroutine changes. if that one False log is printing when you change it to false, then you are either getting a log from the wrong object or you change it back to true before the coroutine resumes execution

tawny grove
#

oh so it might be like

  • jumping is false so it runs function
  • function sets jumping to true
  • anim event sets jumping event to false
  • jump function reruns before the yield can detect jumping as false, setting it back to true
  • repeat
    ?
slender nymph
tawny grove
#

thank you! I was able to fix it

#

ill keep that in mind for the future

naive pawn
raw fiber
#

hey uhm im trying to make a mobil button rn but it doesen work it always gives me error cs0246 because a button isnt assinged but i dont know why its not assinged

#

@slender nymph please dont judge i need to make this and im learning but this is very important to make for me

verbal dome
#

Why do you keep pinging him 😆

frosty hound
#

You don't need to bother people. You need to include the using UnityEngine.UI; namespace.

raw fiber
#

omg thank you

void notch
# raw fiber

You can click ALT + ENTER on the red line and it'll automatically suggest the namespace.