#💻┃code-beginner

1 messages · Page 396 of 1

keen pecan
#

This is the movement vector

slender nymph
#

well now we don't know if it is grounded

#

so this isn't helpful

keen pecan
#

Oh true

swift crag
#

You can ctrl-a tro select all log entries and copy them

rocky canyon
#

ya, that looks okay.. ur gravity is increasing

swift crag
#

it does make a very larger blob of text

keen pecan
rocky canyon
#

i wrote an editor script that prints the console into a .md as a list

swift crag
#

so when isGrounded becomes false, the velocity starts changing

rocky canyon
#

damnit.. i downloaded it

swift crag
#

-5.00 is already plenty to cause a movement with the default minimum move distance of 0.001

#

you'd have to have a framerate of like

#

5000

#

for that to be a problem

#

(if your downwards velocity is very low, then you won't move at all, and isGrounded will become false)

rocky canyon
#

oh, i found his code link sorry bout that @slender nymph

keen pecan
#

lol so should i make it more like .1

swift crag
#

That's not the issue.

#

unless you're getting 5000 FPS

keen pecan
#

ah

rocky canyon
#

what happens if u set ur isGrounded at the end of update loop

keen pecan
#

I am not (its at 60)

rocky canyon
#

instead of at the very beginning?

keen pecan
#

ill lyk

keen pecan
#

Wow

rocky canyon
#

lets go

keen pecan
#

Goated

rocky canyon
#

😉 i had to do the reverse on mine

#

put it at the top instead of the bottom. weird how that works

keen pecan
#

So I guess the issue was with when it ran the first time

slender nymph
#

that shouldn't have made a difference except for maybe the very first frame

swift crag
#

that doesn't make sense, yes

#

unless you were destroying and creating new characters regularly

slender nymph
#

there's only one CC.Move call in there. unless they have some other component calling CC.Move somewhere the only time the property should change is that one time they call Move

topaz fractal
#

i normalized my input but now theres a delay for the character to stop moving

rocky canyon
slender nymph
rocky canyon
#

something to do with the way the logic is writen

slender nymph
# keen pecan That fixed it 100%

change it back then change your log to this and show what it prints: Debug.Log($"Velocity {movement}, Was grounded: {isGrounded}, Will be grounded: {controller.isGrounded}. ({GetInstanceID()})");

swift crag
#

the entire point is that you check if isGrounded got set to true last frame

rocky canyon
swift crag
#

so that you can decide if you're on the ground or not

keen pecan
#

Could also be with the initialization like it started as true but now since its after it starts as false?

rocky canyon
#

i renamed my variable even to wasGrounded

topaz fractal
#

i see, whats the difference?

rocky canyon
#

if yall can fix it w/ it at the top of the update.. i'd love to watch and see how ¯_(ツ)_/¯

swift crag
#

if you access characterController.isGrounded before you call Move, you're asking if you were grounded last frame

keen pecan
#

Also of not the character doesnt start on the ground

swift crag
#

if you access it after calling Move, you're asking if you are now grounded this frame

slender nymph
rocky canyon
#

soo it makes sense for mine to be wasGrounded

#

but.. if i put the isGrounded/wasGrounded at the end of the update.. where it would make sense.. it doens't work correctly

#

i get an issue very similar to his

keen pecan
slender nymph
#

yeah that is one of the worst ways to share logs. i'm not downloading that

keen pecan
#

You can expand it

#

Thats just the logs too

slender nymph
keen pecan
#

oh weird

#

Heres one of the logs when it changes

slender nymph
#

something else is affecting it because it isn't true in the frame after Move is called and the CC sees that it is grounded

keen pecan
#

Yeah this is it when its at the end instead

slender nymph
#

if you're going to change it at the end of the Update method then you need to do so after the log. otherwise you aren't actually seeing the value you are using but the value that it is being assigned to at the end of that method

#

or rather you aren't seeing the actual grounded state of the CC. because something else is affecting it

rocky canyon
#

@keen pecan magic, i can't explain it.. but my controller was once bugging like urs.. and changing where it was in the loop fixed it..

keen pecan
#

Oh true

rocky canyon
#

but i tried to test now.. and mine works either way

rocky canyon
#

sooo... idk

#

lmao

#

apparently i fixed it somehow by adding onto the controller

slender nymph
#

you very likely have some other code calling Move on the character controller

keen pecan
rocky canyon
#

yea, acronex might.. but mine im sure of its only 1 instance, 1 move call

keen pecan
#

I do see the will be working here now

#

Im sure too I click on move and its the only thing that highlights

rocky canyon
#

i might have reverse the name of hte bool

#

and the conditionals

#

ahh, i did.. that why mine works better now..

slender nymph
#

did you actually use the search feature in your IDE

keen pecan
#

I literally only have 1 script rn

rocky canyon
#

then those gizmo's are the animation rigging

#

jus saying

keen pecan
#

Ye

bleak glacier
#

So I'm not sure how to fix this issue. It properly detects that W was pressed and it makes my character move. The only issue is the loop doesn't just stop. It just seems loops the code underneath the keypress. I just want it to run once per key press so it doesn't fly off of the screen.

    {
         if (Input.GetKeyDown("w"))
        {
            yMove = yMove + 0.1;
            Debug.Log("w key was pressed");
        }```
#

public yMove = 0;

#

Just to note that

polar acorn
bleak glacier
slender nymph
#

your issue lies elsewhere

bleak glacier
#

And it continues to rise.

polar acorn
bleak glacier
polar acorn
slender nymph
bleak glacier
polar acorn
#

You are adding 0.1 to a variable

#

Anything more than that would require context

bleak glacier
#

This is the rest of the code. movement = new Vector3(((float)xMove), ((float)yMove), 0.0f); transform.position = transform.position + movement;

The transform.position + movment keeps looping so it keeps adding the movement value

#

I think

slender nymph
#

that's not "looping" it's just likely inside of Update which is called every frame

#

and you never reset your variables back to 0

#

also, is there a reason your xMove and yMove variables are doubles?

bleak glacier
slender nymph
#

that is not a sufficient reason to make them doubles

#

you won't get "more control" that way

bleak glacier
polar acorn
slender nymph
bleak glacier
slender nymph
#

well for one thing it will remove the unnecessary casting

#

and you don't need a 64 bit float since you are doing literally nothing at all that requires that precision when a 32 bit float is just fine and what you need to cast to anyway

#

this is a code channel

golden blade
#

I dont know what to change to make the quality better

eternal needle
golden blade
#

Oh alr

#

where do I go for help with components

bleak glacier
golden blade
#

ty

slender nymph
bleak glacier
slender nymph
#

you know what, fine. i won't help you since you clearly can't fucking read

eternal needle
#

and being pedantic, yes it is worse. You have to cast everytime you want to use it in any unity context and its more memory

#

🤷‍♂️ this is an extremely weird hill to try dying on though. Just swap to floats

bleak glacier
# slender nymph you know what, fine. i won't help you since you clearly can't fucking read

I was asking for help pertaining to something unrelated. If it causes me problems later on I'll fix it. I'm just trying to learn and I don't see how I "can't read." If it doesn't matter it doesn't matter and we can all just move on. There's a section in the rules that mentions not criticizing someone elses approach to a problem. Please try to follow the rules. It isn't hard. All it takes to follow Discord rules is a little bit of reading comprehension.

slender nymph
#

in that case you've done nothing wrong. your code works the way you expect because it is your approach to the problem. and since there's nothing you need help with you can go take your wild takes about having "more control" over your movement because you are using doubles elsewhere

summer stump
eternal needle
#

🤷‍♂️ idk why they even asked why it matters if they ignore every reason on why it matters

slender nymph
#

i'm betting they barely know anything about c# and made the variable a double because they wanted to add 0.1 to it but didn't know how to make that a float

bleak glacier
# slender nymph i'm betting they barely know anything about c# and made the variable a double be...

Happy?

using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float xMove = 0f;
    public float yMove = 0f;
    Vector3 movement;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
         if (Input.GetKey("w"))
        {
            yMove = yMove + .01f;
            Debug.Log("w key was pressed");
        }

         if (Input.GetKey("a"))
        {
            xMove = xMove - .01f;
            Debug.Log("a key was pressed");
        }

         if (Input.GetKey("s"))
        {
            yMove = yMove - .01f;
            Debug.Log("s key was pressed");
        }

         if (Input.GetKey("d"))
        {
            xMove = xMove + .01f;
            Debug.Log("d key was pressed");
        }

        {
        movement = new Vector3((xMove), (yMove), 0f);
        transform.position = transform.position + movement;
        yMove = 0;
        xMove = 0; 
        }
        
    }

    
}
#

Great. You win. A+. Gold star. 10 points to boxfriend.

summer stump
onyx tide
#

Hello thats my first 3d project on unity and i tried to create a HP bar with a tutorial. I write the same line but it doesn't work. Someone can help ?

slender nymph
#

healthSlider has not been assigned to

icy blade
#

hello i tried to put my inputfield on the gameobject script but i cannot put it there like its refuse or not detect it as inputfield ui

summer stump
slender nymph
onyx tide
slender nymph
iron wing
#
        float mouseY = Input.GetAxis("Mouse Y") * MouseSensitivity * Time.deltaTime;

        yRotation = yRotation -= LookInput.z;
        yRotation -= mouseY;
        yRotation = math.clamp(yRotation, -90f, 90f);

        Neck.localRotation = Quaternion.Lerp(Quaternion.Euler(0f, 0f, 0f),Quaternion.Euler(yRotation, 0f, 0f),0.5f);
        transform.Rotate(Vector3.up * mouseX);
        transform.Rotate(0,LookInput.x,0);```

Hi. I made a camera script for my ``Character Controller``. How can I apply ``SmoothDamp`` to this code so I can smooth it all out when you rotate rather than just coming to a complete halt?

the ``LookInput`` is for controller support with Unity's new input system, I figured this was an okay method to apply.
slender nymph
#

taht is suspicious as fuck my guy

keen rampart
slender nymph
#

if you want to share your game, upload the entire build to a reputable site like itch.io or something. and share it in #1180170818983051344

keen rampart
slender nymph
slender nymph
keen rampart
#

ima just delete it

iron wing
swift crag
#

There's no Quaternion.SmoothDamp, unfortunately

#

However, your use of Lerp can be improved a bit

iron wing
#

Lerping doesnt seem to do anything, it acts as if I dont really have one applied

swift crag
#

You aren't using deltaTime at all in the lerp, so it's going to be ultra fast

iron wing
#

ohhh

swift crag
#

yeah, you're moving 50% of the way to the destination every frame

#

zoom

#

Read that page, though. It explains a better way to use Lerp

iron wing
#

that makes a ton of sense let me give that a shot.

#

I will thanks!!

swift crag
#

You can also mix in Quaternion.RotateTowards

#

That way, you don't slowly approach the target forever

#

you always move by at least a bit each frame

keen rampart
#

tf

pliant oyster
#

I have my GameManager now, but when I try to change a variable in it (specifically, use a function inside of it that changes it), it gives me errors. If I print GameManager.Instance it gives me null. How do I fix this?

slender nymph
#

show the relevant code, including where you assign to GameManager.Instance

pliant oyster
#

So the code that accesses it is this:

public class ControlPresetScript : MonoBehaviour, IPointerClickHandler
{
    [SerializeField] public GameObject presetDropdownMenu;
    [SerializeField] public Sprite wadSprite;
    [SerializeField] public Sprite ulrzSprite;
    [SerializeField] public Sprite customSprite;
    public void OnPointerClick(PointerEventData eventData)
    {
        presetDropdownMenu.SetActive(presetDropdownMenu.activeSelf);
    }

    public void SwapPreset(int preset = 0)
    {
        Debug.Log(GameManager.Instance);
        switch (preset)
        {
            case 0:
                gameObject.GetComponent<Image>().sprite = wadSprite;
                GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(0);
                break;
            case 1:
                gameObject.GetComponent<Image>().sprite = ulrzSprite;
                GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(1);
                break;
            case 2:
                gameObject.GetComponent<Image>().sprite = customSprite;
                GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(2);
                break;
            default:
                gameObject.GetComponent<Image>().sprite = wadSprite;
                GameManager.Instance.gameStuff.controls.ChangeControlsToPreset(0);
                break;
        }
    }
}
#

And the relevant code in the GameManager is this:

public class GameManager : Singleton<GameManager>
{
    public GameStuff gameStuff = new GameStuff();
    public class GameStuff
    {
        public Controls controls = new Controls();
        public class Controls
        {
            ...
            public void ChangeControlsToPreset(int preset, KeyCode customLeft = KeyCode.A, KeyCode customRight = KeyCode.D, KeyCode customJump = KeyCode.W, KeyCode customShoot = KeyCode.Space, KeyCode customSprint = KeyCode.LeftShift)
            {
                switch (preset)
                {
                    case 0: // W A D S L-Shift
                        leftKey = KeyCode.A;
                        rightKey = KeyCode.D;
                        jumpKey = KeyCode.W;
                        shootKey = KeyCode.Space;
                        sprintKey = KeyCode.LeftShift;
                        break;
                    case 1: // Up Left Right 0 R-CTRL
                        leftKey = KeyCode.LeftArrow;
                        rightKey = KeyCode.RightArrow;
                        jumpKey = KeyCode.UpArrow;
                        shootKey = KeyCode.RightControl;
                        sprintKey = KeyCode.Keypad0;
                        break;
                    case 2: // Custom
                        leftKey = customLeft;
                        rightKey = customRight;
                        jumpKey = customJump;
                        shootKey = customShoot;
                        sprintKey = customSprint;
                        break;
                    default: // Default to W A D S L-Shift
                        leftKey = KeyCode.A;
                        rightKey = KeyCode.D;
                        jumpKey = KeyCode.W;
                        shootKey = KeyCode.Space;
                        sprintKey = KeyCode.LeftShift;
                        break;
                }
            }
...
slender nymph
#

use a bin site to share large blocks of !code 👇

eternal falconBOT
swift crag
#

Don't clip anything out

#

Share the entire script in a paste site!

pliant oyster
#

Okay lemme do that

swift crag
slender nymph
#

we'll also need to see that Singleton<T> class since it seems to be where the Instanc evariable resides

swift crag
#

ah, yeah, that's where it'll actually happen

pliant oyster
#

The Singleton? Lemme get it

slender nymph
#

and is the GameManager component attached to anything in the scene? and where are you calling SwapPreset on ControlPresetScript

pliant oyster
#

I don't know what you mean with "is the GameManager component attached to anything in the scene", isn't it enough for it to exist in the file system?
I'm calling the SwapPreset in my dropdown.

slender nymph
#

no, it is a MonoBehaviour which means it has to be attached to a gameobject for the Singleton's Awake method to run

lethal bolt
#

I cant find out how to destroy other gameobject? i thougth it was destroy.Gameobjcet.Other but it isnt?

slender nymph
#

pass the gameobject you'd like to destroy to the Destroy method

pliant oyster
#

Okay

slender nymph
#

surely where ever you grabbed that Singleton class from explained how to use it? (i'm assuming you didn't write it yourself since you don't seem to understand how it works)

pliant oyster
pliant oyster
slender nymph
#

if it is a component then it must be on a GameObject to work correctly. and it is a component if it inherits from anything that inherits from Component. like MonoBehaviour.

#

if you are not familiar enough with the engine to know that, i suggest going through the junior programmer pathway on the unity !learn site. it will teach you the fundamentals (of the engine) in a structured, easy to follow manner

eternal falconBOT
#

:teacher: Unity Learn ↗

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

crisp anvil
#

Assigning sprite to Image, how do I do this?

[SerializeField] private Image itemSprite;
itemSprite = slot.Item.itemIcon;

public Sprite itemIcon;
slender nymph
#

this line: itemSprite = slot.Item.itemIcon;
needs to be inside of a method

#

also you need to assign the sprite property on the Image component

polar jungle
#

Hello! I am new to game development and have so far been trying to learn by doing some small projects. The problem is that I still lack a lot of knowledge to even make the smallest projects.

My question is if anyone knows of any good courses to learn C# in Unity? So I can become more familiarised with the language and get started working on my small hobby projects!

wintry quarry
iron wing
#

how do you use the third 'current velocity' parameter for smoothdamp?

polar acorn
shell sorrel
#

well they would want it as a field to store the velocity over frames then reference it, method scoped would defeat the purpose unless its a coroutine

iron wing
shell sorrel
#

there are 2 smooth damps

#

you must be using the Mathf.SmoothDamp right?

#

if so use a float

polar acorn
iron wing
#

Ohh, I didn't realize that. yeah I'm using Mathf.

#

What is the significant difference?

polar acorn
#

But it'll be the same type as your target variable

polar acorn
shell sorrel
#

when damps the movement of a vector the other the movement of a float

#

what are you trying to smooth a postion in space or just a value

iron wing
#

okay okay that makes sense. i was smoothing a float value, so I'd use the Mathf variation

shell sorrel
#

also where are you using it, in Update or a coroutine?

iron wing
#

Update

shell sorrel
#

cool, so i would make the velocity float be a field

chrome shadow
#

why isnt lerpVar being used?

shell sorrel
#

what is your intent, noticed you are passing it in as well, are you expecting this function to adjust the field f as it runs?

chrome shadow
#

yeah i want to change f

shell sorrel
#

make it ref float lerpVar

#

then when you call the function do ref f

wintry quarry
#

Or yes, make it a ref param

shell sorrel
#

also that, if you only ever want to do it via f and not anything you pass in

hoary ice
#

how to make the animator play should end first after proceeding to other method?

cyan folio
#

I animated my legs for a character, but one of the legs goes missing when I click play. Can anyone please help?

teal viper
#

But seriously, you should share some more context and/or video or screenshot demonstrating the issue, as it's not entirely clear from your explanation.

hoary ice
#

my attack state doesnt have animator run in it ony attack
but when i check to the animator nodes it is transitioning to run for a second then go back to attack again

#

why is that?

cyan folio
arctic ibex
#

not quite sure if this is the right spot, but I'm having problems saving. Whenever I press the button to save or load it just says "object reference not set to an instance of an object" (Error attached)

the options code is the only one attached to an object, and save and load are called from a button referencing the object with the options script. All the other save scripts are static.

#

A second ago it was giving me another error but it's just mysteriously stopped even though I didn't change any thing

silver flicker
arctic ibex
#

the reference exist, but for somereason isn't recognised

silver flicker
#

I don't know too much about call errors, but the error says otherwise, have you tried double clicking on the error

#

it should bring you to the line of code where the problem is

#

Hey, I got a problem with raycast detection. My raycasts are set in an array, 24 around a circular object in 360 degrees. I need to call upon each array and see if it collides with the ground, if it does, then it is grounded. That seems to work, as I get a Debug.Log() received, but the majority of the casts, being above ground, keeps isGrounded as false. code - https://gdl.space/iweminuyut.cs

hallow iris
#

hi

#

dose any one know how to fix this

raw token
hallow iris
#

i want it so that the wall apperas as it is on top of the ground

#

any tutorial or blogs to read would be appriciated

raw token
silver flicker
#

no, if any single raycast is touching the ground, then isGrounded is true

#

Currently if more raycasts are in the air then isgrounded becomes false

arctic ibex
raw token
# silver flicker no, if any single raycast is touching the ground, then isGrounded is true

You could reset isGrounded to false prior to the loop, then only have a positive ground collision set isGrounded to true and get rid of the else. Alternately/additionally, if this is these raycasts only function, you could also break out of the loop at that point so save on physics queries - no need to keep checking them if you know you already know you're grounded.

silver flicker
#

Oh ok got it. Ill try that thanks

raw token
arctic ibex
raw token
hallow iris
arctic ibex
#

The code for SaveData hasn't changed

raw token
elder osprey
#

I am trying to make a sprite change to a random one, but currently I am setting it in FixedUpdate() meaning its changing the sprite 50 times a second. Does anybody know a way I could make the sprite change with a delay of my choosing?

stone elk
#

why does my game play differently when i go full screen? My character moves slower?

chrome shadow
#

how do i use MenuUI.GetComponentInChildren<TMP_text>(); to get the "TMP_text" part from "ButtonText"

raw token
elder osprey
#

Nevermind, I figured it out, thank you!

cyan folio
raw token
# chrome shadow how do i use MenuUI.GetComponentInChildren<TMP_text>(); to get the "TMP_text" p...

If you have multiple objects with TMP_text components in that subhierarchy, that could get a little messy/inefficient - I think you'd have to filter through all the results and test each game objects' name, which is also fragile as you would need to remember that if you ever change the GO's name you also need to change the name you're filtering for.

Ideally, if something depends on that specific TMP_text component, it would be better to cache a reference to it either where it's needed, or in some script responsible for controlling that UI. Cut out the middleman and directly provide the reference so that you needn't write code to search for it.

The easiest way would be just use a

public TMP_text ButtonText;

field in the dependent class, and drag the TMP_text component to it in the inspector.

arctic ibex
raw token
# arctic ibex K so I just manually set current res to the screens resolution and tried again a...

I'm not sure how you've set it, but if the NRE is still on that res[0] = options.currentres.width line, then the only two possibilities are that res is null (which I don't believe to be the case - since it's a public field I think Unity should initialize it by default?), or options.currentres is still null there for some reason. You can of course test directly to figure out which is null:

if (res == null)
  Debug.Error("RES IS NULL!");

if (options.currentres == null)
  Debug.Error("CURRENTRES IS NULL!");

In the longer run, learning to use your IDE's debugger always pays dividends - it allows you stop code execution, step through it line by line, and examine all of the values of things in memory.

arctic ibex
#

K so that didn work... do i test width and height manually? it just said that resolutions can't be null right? that's what that means?

#

okay so it says ints can't be null... so I can't test width and hegiht seperatly. Which i guess means currentres being null isnt the problem then?

chrome shadow
slender nymph
raw token
arctic ibex
#

wait it's just int[] = new int[] isnt it

arctic ibex
slender nymph
#

you have the wrong attribute on the SaveData type

arctic ibex
slender nymph
#

look at the attribute you've placed on the SaveData type. it should be Serializable

arctic ibex
#

okay so uh.... this happened. I guess it wasn't deserialising before so it never noticed it or something? anyway, heres the error and the code in question.

slender nymph
arctic ibex
#

oh and another sharing violation but I'm guessing that's just causd my this error

arctic ibex
#

Thanks for telling me, I 100% would have kept using that forever otherwise

slender nymph
#

it honestly wouldn't be a huge change if you just switch to json utility or something, there should be plenty of tutorials for how to use that for save/load

arctic ibex
slender nymph
#

well binary formatter can potentially allow malicious code execution on yoru players devices, especially if they share save files and stuff

arctic ibex
queen adder
#

anyone know the command to bring up the unity visual studio set up agaon?

slender nymph
queen adder
#

cheers

#

!ide

eternal falconBOT
slender nymph
#

literally right above the one with all the commands

queen adder
#

oh haha i saw the code and used it XD sorry

slender nymph
arctic ibex
# slender nymph i mean, i guess

okay that's good cause i can NOT be bothered to change it when i need to submit this game in like 4 days and it's only half done

queen adder
#

hummm ok weird so small issue the visual studio vode editor altho set up correctly. is claming that my void on update isnt used... i dont know why. im doing some mesh defromation at run time, and testing in the editor but it isnt working. idk why.

slender nymph
#

well where do you call OnUpdate?

hallow iris
#

i have a code related question i want to make a hord based spawning system over a random range over a 2d top down feild and idea how sould i go arround this?

#

like any like blogs to read or tutotials would be appriciated

slender nymph
#

you can use Instantiate to spawn an object, methods on the Random class to generate random numbers for the positions and the like, and a loop

queen adder
#

im asking in their servers as well but i dont know what i did wrong as that exact same code works in another project

slender nymph
#

if it is a message sent from the vrchat sdk then naturally vs code wouldn't see that you are using it. of course if you have problems with anything related to the !vrchat sdk, you can ask in their discord server 👇

eternal falconBOT
queen adder
#

ok guess im i cant ask here sorry.

quick kelp
#

or if you really need these animations to be in unity only

#

copy the X in your postion tab when the animations not playing

#

and paste it for it each frame

#

that should technically do it

cyan folio
quick kelp
#

ok quick question I'm about to work on a save system for me game is it possible to save DontDestroyOnLoad objects

languid spire
quick kelp
#

alrighty thank you

queen adder
#

hey i have a problem when i install unity and direct it to my E drive it takes memory from the C drive and when i install unity editor also directed to E drive it starts downloading in C drive

languid spire
queen adder
languid spire
vernal bone
#

Quick question.
I have a situation where multiple objects fire a OnTriggerEnter event (Bullets entering an enemy object), and i have a problem with processing this situation.
Is there some way to look at all of them at once, like a list of currently triggering objects?
Or is there other good ways to handle that?

stone elk
#

can i change size of player without affecting its circle collider.

burnt vapor
#

Sounds like you have a different issue that is reason for this question?

stone elk
#

its not a big deal. nvm

burnt vapor
#

Maybe you can try this instead and call this each frame on your enemy

#

Not sure how much better this would be over just checking using the OnTriggerEnter method, though. Why would that not work here?

slate haven
#

I have pickups spawning in my game by object pooling in which there are pools (list). I want to deactivate a certain pool from spawning for a specific condition. What do i do?

vernal bone
# burnt vapor Not sure how much better this would be over just checking using the `OnTriggerEn...

it fails (sometimes) when i count player score. Each hit adds a bit.
And when enemy object is killed, it adds incorrect amount of score. Sometimes more, sometimes less, but everytime that is caused by multiple sumiltaneous fatal blows. It's probably on surface and i'm just dum

here's code if you interested:

    public void GetDamage(int dmg){
        int prevHP = HP;
        HP -= dmg;
        int score;
        if (HP > 0){
            score = prevHP - HP;
        }
        else{
            score = prevHP;
        }
        InterfaceSingleton.Instance.AddScore(score * 10);
        if (prevHP > 0 && HP < 1){
            Destroy(gameObject);
            InterfaceSingleton.Instance.AddScore(500);
        }
    }
burnt vapor
vernal bone
#

if i get it correctly, all triggerenter events processed in some order, not simultaneously, so it should be fine, but it is not

burnt vapor
#

I never heard it would not trigger

vernal bone
#

oh, i guess i got what's wrong

burnt vapor
#

Because Unity is synchronous and that doesn't happen

#

I'm kind of confused on the root issue

#

How does it incorrectly add score?

vernal bone
#

I fixed that. Problem was that I did not check if prevHP > 0
At first it added more points that it should, because I didn't handled it properly, and now it added less for the same reason.

#

@burnt vapor big thanks anyway UnityChanThumbsUp

carmine sierra
#

where is this in the new version

#

conditions

#

cause my one doesnt show any

eternal needle
carmine sierra
#

why do i need to do SetBool/Trigger for animation booleans/triggers

#

and why do triggers exist

#

are they not just bools

burnt vapor
#

They are two completely different things google

carmine sierra
#

isnt a trigger just a one way bool

carmine sierra
frosty hound
#

So you can transition animations

vernal bone
#

Another small question.
"yield return" in this coroutine just makes a while loop wait for some time before another loop?

private IEnumerator Coroutine(){
  while(true){
    sumCode();
    yield return someTime;
  }
}
vernal bone
#

kinda pseudocode btw

languid spire
#

then you should say so, we are not mind readers

vernal bone
#

well, i tried to make a syntactically correct example that does nothing, but shows intention, but failed to do so i guess. noted.
thanks anyways

burnt vapor
#

The point is the underlying enumerator (which coroutines use directly) that can be iterated in steps. That's also how Unity pauses Coroutines to simulate delays

vernal bone
burnt vapor
#

You could technically make a similar system like a Coroutine. Unity just does it themselves when you call StartCoroutine

bleak condor
#

my character is not collding with the tilemap. they have the same layer and the tilemap has a tilemap collider

carmine sierra
wintry quarry
#

Show the inspectors of the objects you expect to collide

carmine sierra
#

if a public variable is not being referenced from another script, but you need it to be public to reference something else, would it be written as "variableName" or "VariableName"

bleak condor
#
  1. tilemap
#

my game also gets this error a lot but i dont think it relates to collisions

languid spire
short hazel
frosty hound
frosty hound
carmine sierra
#

its not like you would accidentally reverse the trigger

bleak condor
frosty hound
#

So you can fire off an animation transition without having to manage the value of a bool. It's a one time call.

carmine sierra
#

oh okay

#

so you can trigger it multiple times?

#

instead of flipping on then off then on again

short hazel
#

Triggers auto-reset when the transition is consumed

carmine sierra
#

yeah

#

okay i get it

lethal bolt
#

Isnt this how you get the Rigidbpody?

languid spire
carmine sierra
#

is it a good idea when programming to use as many methods as possible

bleak condor
carmine sierra
#

to make it look clean and to allow you to isolate the methods code

languid spire
bleak condor
#

theres no code its just like the collision between 2 game objects

lethal bolt
#

debug.log

queen adder
short hazel
# lethal bolt Isnt this how you get the Rigidbpody?

Yes it is one of the ways to retrieve a reference to a Rigidbody
Whether it's correct in your context cannot be confirmed though, but since you're posting this I guess something is wrong with it.
Always, if you have errors, post them in the original question

lethal bolt
short hazel
#

If that was the case, you'd get a NullReferenceException

#

So either the code doesn't run, or it runs but the force is so small that you can't see any movement

languid spire
lethal bolt
queen adder
short hazel
languid spire
queen adder
languid spire
swift crag
#

note that this has nothing to do with code

#

it's also not exactly a unity problem in general. free up some space.

#

it won't be permanently used; it's just where Unity keeps data that's being staged

queen adder
lethal bolt
#

Why cant i use Random?

swift crag
#

did you read the error?

lethal bolt
#

yes

swift crag
#

okay, so you know why you can't use Random, then

#

it tells you exactly what the problem is

lethal bolt
#

huu?

swift crag
#

'Random' is an ambiguous reference between 'UnityEngine.Random' and 'System.Random'

#

What do you not understand about this error message?

#

I can't help you if you just make confused noises

lethal bolt
swift crag
#

I have no idea what that's supposed to mean

lethal bolt
#

'UnityEngine.Random' and 'System.Random' The diffrent between these.

languid spire
languid spire
lethal bolt
#

Oh

#

Okay

swift crag
#

Different things generally have different names.

#

You can clarify which class you want to use with another using directive.

languid spire
#

And your question is?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

hallow iris
#

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

public class enemyDamage : MonoBehaviour
{
public wallHealth wHealth;
public float damage;
// Start is called before the first frame update
void Start()
{

}

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

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Wall") )
        {
        wHealth.health -= damage;
        }
}

}

#

can any one tell

#

me what is causing this error

#

and how can i fix this

short hazel
#

!code

eternal falconBOT
short hazel
#

Follow the instructions above so the code is properly formatted
at Assets/Scripts/enemyDamage:25
Your error happens on line 25 of the enemyDamage script.

timid hinge
#

hi guys im having a problem but i dont know where is it im creating a game like vampire survivors and i have animations for all type of weapons and everything but the animation is not working on any weapon

hallow iris
#

how can i fix this?

short hazel
#

Some variable on line 25 has no value (it is null), but you're trying to do something with it anyway

shell sorrel
#

wHealth is never assigned a value

#

guessing you forgot it in the inspector

hallow iris
short hazel
#

You changed the code and forgot to assign the script again. Drag-drop the object which has the wHealth script on it

hallow iris
#

ok

#

i want to assing a tile map to this to which a script is attached how should i do this

#

i want this wall to have health and if some one attacks it it looses health

polar acorn
hallow iris
normal valve
#

Hello, not sure where to put this as there isn't a channel for it. My Project won't update it's Player Version to file when I make a change (Project Settings > Player > Version). Does anyone know why? I have Project Settings as a submodule in Git and we use it to differentiate our software versions. Git obviously can't see a file change as there isn't one. Thanks

shell sorrel
#

which file are you looking at?

#

also hit save project from the file menu after making changes to settings

#

also project settings as a submodule in git is very weird behaviour and way to set things up

swift crag
#

that is...odd, yes

pine bone
#

Hello guys, i have a problem with my gun system (2D). The gun works perfectly when i play the game for the first time. But if i reload the scene (pressing restart level button) i suddenly cant shoot the gun anymore, i need to restart the game and join again for it to work. By the way this only happens in the built version and not in editor. Thank you in advance

shell sorrel
#

you would need to descrive more about how your reload works, and how that differs from how the game does it on first launch

#

and provide what errors you are getting when you try and shoot, feels like its losing reference

pine bone
shell sorrel
#

but the logs should tell you that

pine bone
#

And i cant even debug because it doesnt happen in editor

shell sorrel
#

sure you can

wintry quarry
pine bone
#

how

shell sorrel
#

what platform is it

pine bone
#

windows

shell sorrel
#

PC or like android or something

#

launch it in the terminal

wintry quarry
#

basically all the same ways

shell sorrel
#

or attach the console from the editor too it

pine bone
shell sorrel
#

can even attach your ide debugger if you build in dev mode with script debugging

pine bone
#

do i open command prompt and type "gamename".exe

shell sorrel
#

well easist way would be to just get the log file

pine bone
shell sorrel
#

%USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\Player.log

#

you will need to replace parts of that path based on your org and product name

pine bone
#

DontDestroyOnLoad only works for root GameObjects or components on root GameObjects.

#

it only has this error i think

polar acorn
shell sorrel
#

also i would delete teh log, then reproduce the error

#

then check it

shell sorrel
#

that way you only get stuff from 1 gameplay session

pine bone
shell sorrel
#

ok and look at where that error is, and figure out why

pine bone
#

NullReferenceException: Object reference not set to an instance of an object
at GunShooting.Update () [0x00050] in <febfd361b8104404ba670889ca3da885>:0
at PlayerShooting.Update () [0x00000] in <febfd361b8104404ba670889ca3da885>:0

#

Is there a way to get the line

#

number

wintry quarry
#

It should generally be pretty obvious looking at the code though for an error like this

polar acorn
shell sorrel
#

it takes a bit of work, but seeing the callstack should be able to get you close enough, also yeah make sure development build is checked

pine bone
#

 public virtual void Update()
 {


     if (!canFire)
     {
         timer += Time.deltaTime;
         if (timer > 1 / gun.firerate)
         {
             canFire = true;
             timer = 0f;
         }

     }
     bool ShouldRotate = !(transform.parent.eulerAngles.z < 90 || transform.parent.eulerAngles.z > 270f);
  
         foreach (Transform childObject in transform)
         {
             if (childObject.GetComponent<SpriteRenderer>() != null)
             {
                 childObject.GetComponent<SpriteRenderer>().flipY = ShouldRotate;
             }
         }

     
   
 }```
pine bone
wintry quarry
shell sorrel
#

going to assume its gun

#

or the GetComponent call is failing

wintry quarry
#

or transform.parent is null

#

GetComponent should be fine since there's an if

shell sorrel
#

so would look into how those are defined

pine bone
shell sorrel
#

well try a build that gives line numbers

#

and it will be very obvious

wintry quarry
#

you;d have to show more context

shell sorrel
#

or if this is DDOL it would lose references as other stuff unloads

pine bone
#

bool ShouldRotate = !(transform.parent.eulerAngles.z < 90 || transform.parent.eulerAngles.z > 270f);

this line gives the error but its from a different gun object

#

that has no parent

wintry quarry
#

If it's expected for you to not hav a parent sometimes, you need to make sure in your code that you heck for that before using it.

pine bone
#

its a different object

#
        if ( (Input.GetMouseButtonDown(0) || (Input.GetMouseButton(0) && gun.isAutomatic)) && canFire && isPickedUp && !GameManager.Instance.isPaused)
pine bone
polar acorn
pine bone
#

the gun is set in the inspector

shell sorrel
#

add some log statements to check on thing and test assumptions

pine bone
#

and the bug was there before i added gamemanager so it cant be null

#

why does it only happen in built versions and not in editor

pine bone
# polar acorn Then either `gun` or `GameManager.Instance` is null
NullReferenceException: Object reference not set to an instance of an object.
  at CameraShakeManager.SetupScreenShakeSettings (ScreenShakeProfile profile, Cinemachine.CinemachineImpulseSource impulseSource) [0x0003b] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\Managers\CameraShakeManager.cs:51 
  at CameraShakeManager.ScreenShakeFromProfile (ScreenShakeProfile profile, Cinemachine.CinemachineImpulseSource impulseSource) [0x00001] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\Managers\CameraShakeManager.cs:39 
  at GunShooting.Shoot () [0x0003a] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\GunShooting.cs:31 
  at PlayerShooting.Update () [0x0004a] in D:\...\UltraUnityFolder\2D Platformer\Assets\Scripts\Gun Scripts\PlayerShooting.cs:18 ```
#

it turns out that the guns shake profile gets deleted

#

for some reason

fleet coyote
#

Hi! I am kinda new to unity. I followed a movement tutorial(using get axis raw input and moveposition) and then tried implementing dashing on my own via AddForce. This however doesnt work for me. I tested with a new script and it seems like my movement script "blocks" all Force functions. Why is that?

      speed = GetComponent<stats>().speed;
      position.x = Input.GetAxis("Horizontal")*speed;
      position.y = Input.GetAxis("Vertical")*speed;

      rb.MovePosition(rb.position + position);
fleet coyote
#

2d

pine bone
#
speed = GetComponent<stats>().speed;
      float x = Input.GetAxisRaw("Horizontal") *speed;
      float y = Input.GetAxisRaw("Vertical") *speed;

      rb.AddForce(new Vector2(x,y));```
wintry quarry
fleet coyote
#

That was my guess too but I can't think of a workaround?

raw token
wintry quarry
pine bone
# wintry quarry Because your code is just explicitly setting the position to an exact place. Na...

        impulseListener.m_ReactionSettings.m_AmplitudeGain = profile.listenerAmplitude;

this is the line that gives me null reference exception error, do you know why?

full function:

    private void SetupScreenShakeSettings(ScreenShakeProfile profile, CinemachineImpulseSource impulseSource)
    {
        impulseDefinition = impulseSource.m_ImpulseDefinition;
        impulseDefinition.m_ImpulseDuration = profile.impactTime;
        impulseSource.m_DefaultVelocity = profile.defaultVelocity;
        impulseDefinition.m_CustomImpulseShape = profile.impulseCurve;

        impulseListener.m_ReactionSettings.m_AmplitudeGain = profile.listenerAmplitude;

        impulseListener.m_ReactionSettings.m_FrequencyGain = profile.listenerFrequency;
        impulseListener.m_ReactionSettings.m_Duration = profile.listenerDuration;


    }
}```
fleet coyote
#

Thanks for the help. I will try to implement your ideas.

polar acorn
wintry quarry
pine bone
#

the impulse listener is set here

polar acorn
#

Try logging them to see what's null

#

then you can try to find out why with actual information

pine bone
polar acorn
pine bone
#

also theres no other code affecting it

polar acorn
#

Presumably because you're doing something in code that removes it in build mode but not in the editor

pine bone
polar acorn
pine bone
#

i dont even have any other code that affects the camera

#

i dont know

polar acorn
#

Have you tried using logs to find out what is null in the first place

#

It's pointless to try to diagnose a why without a what

pine bone
#

its the impulse listener obviously

polar acorn
polar acorn
#

Well, I suppose if profile was null it'd error the line before that, but it still could also be m_ReactionSettings

pine bone
polar acorn
#

both are used for the first time on the line throwing the error

#

So, log impulseListener and impulseListener.m_reactionSettings. Do them in two separate logs, so if the first one prints null, you'll still see it before the second one throws an NRE

pine bone
#

i did this and it worked

#

so mreaction settings isnt null

polar acorn
# pine bone i did this and it worked

Okay good. That is also sufficient to check which one it is. So, now you know impulseListener is null. You've dragged it in to the inspector of this specific instance of this script, so one of the following two things is happening:

  1. There exists another copy of this script which does not have impulseListener set
  2. impulseListener becomes null at some point, either because the variable is set to null or the object you were referencing impulseListener from was destroyed
pine bone
#

so the impulselistener becomes null

polar acorn
#

Such as when the scene it was in was unloaded

pine bone
#

also i made the camerashakemanager not destroy on load

#

could it be related to that

#

anyways i think it works fine right now, thank you so much for helping @polar acorn @wintry quarry @shell sorrel

heavy garden
#

should I add anything here like to create a save or something

#
using UnityEngine;
using UnityEngine.SceneManagement; // This is needed for SceneManager

public class NewGameButton : MonoBehaviour
{
    // This function will be called when the button is clicked
    public void StartNewGame()
    {
        // Replace "StartScene" with the name of your scene
        SceneManager.LoadScene("StartScene");
    }
}
#

how would I do that

frosty hound
#

What is "something"?

#

You actually have to know what you're trying to achieve

heavy garden
polar acorn
frosty hound
#
  1. Setting up save data is a big topic I'm not going to try to distill down into a few sentences
  2. You create a new save where it makes logical sense ... such as when you start a new game
heavy garden
#

and playerprefabs confuse me

frosty hound
#

As I said, I'm not going to try to distill down into a few sentences. I don't have the time to actually explain a whole data structure to someone. You can start by looking up tutorials on how to save data, though if PlayerPrefs confuses you then you have a lot more ahead of you.

It also really depends on what kind of data you're planning on saving.

heavy garden
#

mainly player position, inventory items, and current objectives

frosty hound
#

Then no, playerprefs wouldn't be used here. You will have to create your own save data class, and save that using JSON (for example).

lavish jolt
#

Hello. How can I know that enemy and player have no obstacles between them?

lavish jolt
#

And what should be the direction of the ray if I cast it from enemy? Player position?

polar acorn
#

The direction between the two objects

swift crag
#

a position is not a direction

languid spire
carmine sierra
#

when the guy on learn unity makes a mistake, is it scripted or real

unreal path
#

hi i recently started coding and now i want to have a small text pop up when you collect an item, everything should work fine in theory but i cannot drag my text from the hierarchy to the inspector and when i try to just select it i get "type mismatch"

bleak glacier
#

Hey so I'm using Unity 2D and I have a funky problem. I have rigid body 2ds and box collider 2ds on my player and game object. Whenever they collide though, the game object and sometimes the player end up off centered and messed up. It's really weird and it's kind of a big problem. I tried including a script to set their rotations to 0,0,0 but that didn't help.

raw token
unreal path
raw token
swift crag
#

If you're trying to do that -- such as dragging a scene object into a prefab's inspector -- then it will not work.

unreal path
#

i have a text-object in my canvas and i try to drag it into the inspector from my other object which should make the text invisible and visible again... idk if that helps

swift crag
#

it does not help very much, no

#

screenshot what you're doing

#

show us the inspectors of the objects you're using, and show us that they both exist in the scene

wintry quarry
unreal path
swift crag
#

You are trying to reference a scene object from a prefab.

#

You can't do that.

unreal path
#

so i have to make the text a prefab too?

swift crag
#

No, because then it wouldn't exist in the scene

#

you could have an instance of the prefab in the scene, sure

#

but you could not reference that specific instance from the enemy prefab

#

You need to assign this reference when you spawn the enemy.

wintry quarry
#

I would reverse the dependency

#

have the UI thing read data from the Enemy instance in the scene after it's spawned

unreal path
#

im really new i just figured it would be the easiest to toggle the visiblity of the text right when i check collision

wintry quarry
#

You can use the singleton pattern too, if there's only one of these UI things.

swift crag
#

If you're extremely new then you really ought to use !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

unreal path
#

aight guys i think i have an idea of how to fix, ill just try around if anything comes up i'll update and ask again :) thanks everyone

bleak glacier
#

There's a little bit of wiggle still but nothing game breaking anymore

nocturne violet
#

hey does anybody know better alternatives for WaitForSeconds? Something that can be in the same function and more easy to read

swift crag
#

your question does not make sense

swift crag
#

If you're asking about something that can "delay" Update(), you can't

nocturne violet
#

yeah

summer stump
swift crag
#

I don't know what "in the same function" means.

spare mountain
swift crag
#

other than "not in a coroutine"

nocturne violet
#

ah, ok

rich adder
#

make timer inside coroutine with deltaTime thinksmart

spare mountain
nocturne violet
#

im not trying to make it in update

spare mountain
#

oh alr

rich adder
nocturne violet
#

im trying to make the delay in my own funcion

#

that isnt the one that WaitForSeconds is used for

spare mountain
#

can you make your function a coroutine?

swift crag
#

Show exactly what you're trying to accomplish here.

nocturne violet
#

im trying to make a timer that doesn't used an ienumerator

#

a void

swift crag
#

it's not "a void"

#

it's a method that returns void

swift crag
nocturne violet
#

oh

#

ok

spare mountain
#

I fail to see why you need to avoid coroutines so bad

nocturne violet
#

im just trying to mess around with unity rn

swift crag
#

again, this will not let you make the Update method "wait"

#

if that's what you're trying to achieve

nocturne violet
#

alr

#

thank you

rich adder
#

    IEnumerator Delay()
    {
        yield return new WaitForSeconds(1);
        var time = 0f;
        var timer = 1f;
        while(time < timer)
        {
            time += Time.deltaTime;
            yield return null;
        }
        //Timer done do something?
    }```
They're both legible to me :shrug
nocturne violet
#

i know but i was just wondering if there was a different way on doing a wait function

rich adder
#

many ways lol

swift crag
#

It doesn't get much easier to read than yield return new WaitForSeconds(1f);, though

#

it's pretty obvious what this does: wait for one second

nocturne violet
#

ah ok

#

thank you

polar acorn
swift crag
#

true

spare mountain
#

lol

swift crag
#

well

#

your game takes a little nap

spare mountain
#

yeah I could imagine

swift crag
#

so it's great if you don't want your game to work

carmine sierra
#

the ub should automatically refer to the y position right?

swift crag
#

it's a poor fit for the "my game shouldn't freeze" crowd

spare mountain
#

gonna thread.Sleep(Mathf.inf); rq

swift crag
#

you are comparing it to transform.position.y

#

that's very manual

carmine sierra
#

yeah exactly

nocturne violet
carmine sierra
#

so would it understand that i am saying the y position needs to be greater than or equal to a y pos of 45?

#

or would i need to say somehting...position.y

swift crag
rich adder
swift crag
#

All that C# cares about is that you have floats on both sides.

#

It does not matter where those floats came form

carmine sierra
#

okay thanks

nocturne violet
rich adder
#

Unity does some voodoo magic with it to make ti a " coroutine "

swift crag
rich adder
nocturne violet
#

oh

spare mountain
rich adder
swift crag
#
IEnumerator Foo() {
  yield return "Hello";
}

When you declare a method that returns IEnumerator and has at least one yield statement, you get an iterator method

rich adder
#

but I do know what its doing , I believe you're one who told me about it

swift crag
#

An iterator method returns an IEnumerator. This is an object that can give you values one at a time.

#

Each time you hit a yield, the enumerator stops running and produces a new value.

#

Unity repeatedly asks the enumerator for values until it runs out.

carmine sierra
#

if i say velocity(0,0,0) would it stop continuing forces from acting on the item (granted no forces are being applied at that time)

swift crag
#

That's how coroutines work.

#

If you yield special kinds of objects, like WaitForSeconds, that changes how often Unity asks for new values

#

Normally, it asks for one new value per frame.

spare mountain
#

might as well just freeze its location though

swift crag
#

Therefore, if you do this:

IEnumerator Hello() {
  while (true) {
    Debug.Log("HI!");
    yield return null;
  }
}

and start a coroutine with it, it'll log "HI!" once per frame

#

each time it hits yield, the enumerator pauses

#

and unity resumes it once per frame, by default

dense root
#

https://gdl.space/liloviqoto.cs

Right now I have an array-based button system, but the problem is that when I want to select the "left" or "right" button it is actually based on the position of the array, not the button relative to world-space. How do I go about doing the latter?

swift crag
#

although, one thing: if you use UI components with navigation enabled, this will happen automatically

rich adder
#

doesn't ui have navigation flow control you can adjust?

swift crag
#

you can also manually specify the navigation flow

#

This should actually be working fine by default. Are you not using Unity UI buttons?

dense root
#

This is what I'm using

swift crag
#

so instead of having your code move around with Input.GetKeyDown, you'd just be moving a UI selection around

#

when you hit Enter with a Selectable selected, it'll receive a submit event

#

which will cause a Button to fire its onClick event

#

so actually...just get rid of al of that code and it should work

#

the only problem is that you need to get an initial selection

#

you can call Select on the first button when the menu comes up

carmine sierra
#

just the velocity at that moment

dense root
#

Okay let me tinker with the code and see what I come up with

spare mountain
dense root
#

I just want the higihlights to come up once the player presses their arrow keys

swift crag
#

Then don’t immediately select something

#

But you’ll need to then select something through code when the player presses an arrow key

dense root
#

Ahh gotcha

#

Tysm

swift crag
#

note that if you click off of a Selectable, you'll wind up with nothing selected

swift crag
carmine sierra
#

right now i just set velocity to zero

swift crag
#

you could add force when you're getting close to the bounds

spare mountain
#

seems pretty simple

swift crag
#

and then forcibly stop the player when they get too far

spare mountain
carmine sierra
#

i think i have a solution, but nah i dont want an invisible wall

spare mountain
carmine sierra
spare mountain
#

have fun

carmine sierra
dense root
#

I put this in Update but it freezes up the selection, where is a better spot to check for arrow inputs?

    private void Update()
    {
        // Check for arrow input so that we can automatically select an item
        if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow))
        {
            answerButton[0].Select();
        }
    }
pine bone
#

hello, whats the best way to store users owned skins? should i create a skin class and make it serilizable, and create a list with that

carmine sierra
#

i have an idea that i should only use forces and velocity since translate seems to be very jittery. is this a good idea or is there a way to counteract that jitteryness (i remember seeing something called smooth something)

swift crag
#
EventSystem.current.currentSelectedGameObject
wintry quarry
swift crag
#

we're switching to that :p

#

also, if the Automatic navigation misbehaves (it can find the wrong Selectables), you can manually configure it

#

I do that via script for most of my menus

carmine sierra
#

nvm stupid question

spare mountain
swift crag
#

yes: if you're using a rigidbody, you should tell it to move

#

instead of changing your Transform and then letting the rigidbody find out about the new position later on

dense root
#

Okay so the arrow keys work perfectly tysm for telling me about the EventSystem. But now my mouse doesn't register the clicks... thoughts?

carmine sierra
dense root
fossil ether
#

Hey guys, has anyone ever tried to use the flow field pathfinding on a unity terrain using the height of the terrain as the cost field

swift crag
#

I've certainly done gradient ascent/descent before for game AI

fossil ether
#

Oops sorry, I'll remove the other one

spare mountain
swift crag
fossil ether
swift crag
#

I did it with Gaussian functions, which are easy to compute derivatives for

swift crag
#

It will have some information in the bottom of the inspector

#

perhaps something is blocking the buttons

#

(see what your cursor is reported as hovering over)

swift crag
fossil ether
#

Isn't it too computationally expensive

swift crag
fossil ether
#

I'm actually trying to implement the flow field for an rts too since I thought using A* for every single moving unit would slow down the game a lot

swift crag
#

you need a direction to move in

fossil ether
#

I don't use the cost field to calculate the vector field

swift crag
#

ah, the cost field is separate

fossil ether
#

I use it to calculate an integration field which is basically just bfs to calculate the best cost of each cell

#

Then I try to look for the lowest best cost difference between the current cell and its neighbors that are at the same level

#

But some cells don't get vectors assigned to them

#

And some vectors doesn't even make sense lol

dense root
swift crag
#

No, this has nothing to do with your mouse problem

dense root
#

Oh

swift crag
#

however, you're using the new input system here, and it doesn't provide much information in the Event System for some reason

#

this is all I get in my editor

swift crag
dense root
#

Yup, that's how I tested out the system before

#

Somehow this is overriding it

    private void Update()
    {
        // Check for arrow input so that we can automatically select an item
        if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (EventSystem.current.currentSelectedGameObject == null)
            {
                answerButton[0].Select();
            }
        }
    }
swift crag
#

did you comment the code out and try it?

dense root
#

Oh shit I just did that, huh I broke something

#

mumbles angrily to oneself

fossil ether
ivory bobcat
#

You should tell folks what's driving you mad

fossil ether
#

I can't quite pin point the issue either but my vector field doesn't make sense and some cells don't have any vectors

#

The cells missing the vectors happened after i added the height check in the flowfield function

#

I use it to calculate an integration field which is basically just bfs to calculate the best cost of each cell
Then I try to look for the lowest best cost difference between the current cell and its neighbors that are at the same level
But some cells don't get vectors assigned to them
And some vectors doesn't even make sense lol

#

This is what i do in summary

dense root
#

https://gdl.space/axejoqiwen.cpp

Hmm so I checked to make sure Raycast Target is selected and tried to Debug.Log the Answer Button being clicked but I'm still shooting a blank here.. any ideas?

swift crag
dense root
swift crag
#

Show the inspector for the Correct Response object

dense root
swift crag
#

This object will block anything under it

#

so that could be an issue

dense root
#

I'm wondering if the answer box parent object itself is blocking it

swift crag
#

Parents go beneath children

#

I would slap a brand new button on and see if it works

slender nymph
#

could it be because the button has no sprite assigned for the graphic raycaster to detect?

swift crag
#

An empty image can still get hit by a graphic raycaster

dense root
#

Interesting... so my test button doesn't work either

    void Start()
    {
        // TEST BUTTON
        TESTBUTTON.onClick.AddListener(OnClickButtonClick);

    private void OnClickButtonClick()
    {
        Debug.Log("Test button clicked!");
    }
swift crag
#

is it a completely normal button you created from the GameObject menu?

#

if not, do that

dense root
#

Nope it was a duplicate, I'll do that.

#

Yeah no dice...

swift crag
#

Where did you put that button in the hierarchy?

dense root
swift crag
#

okay, that should be atop everything else in that canvas

#

Do you have any other canvases? You can search the hierarchy for them with t:canvas

carmine sierra
#

for this question, how is it that the class begins right above the player variable assignment and no player variables are initialised?

swift crag
#

This is not valid code.

carmine sierra
#

exactly

swift crag
#

It's missing a player field

dense root
carmine sierra
swift crag
#

Right.

carmine sierra
#

yess

dense root
#

Oh shoot maybe it has something to do with the Fader I added...

carmine sierra
#

can you get a component for a private variable

#

or does it need to be public

swift crag
carmine sierra
#

like private Animator anim;
anim = GetComponent<...

swift crag
#

GetComponent checks if there's a certain kind of component on a game object

swift crag
#

(unless they're readonly or something)

carmine sierra
#

idk what a field is

#

is that a variable

swift crag
#

a field is a variable declared as part of a class (more generally, inside of a type)

#

it's a kind of variable

carmine sierra
#

oh okay

swift crag
#

local variables are another kind of variable

#

they're declared inside of a function

carmine sierra
#

so wym you can always assign to it, you cant assign another script to it if it is private right?

#

from another object

swift crag
#

It determines who is allowed to see that field.

#

private means that only the owning class can see it.

#

public means that any class can see it

dense root
#

Shoot it's the Fader I added! lol darn

#

The fader was overlaid on the screen, blocking mouse input

carmine sierra
#

cause you cant assign another script to a private field right

swift crag
#

That is not what private means

#

The only thing that private means is that other classes can't see that field.

#

Nothing else.

carmine sierra
#

okay

#

i get it

swift crag
#

So if your question is anything other than "does it affect who can see the field?", the answer is "no"

#

(well, it does also make Unity not serialize the field by default)

carmine sierra
#

so you can use a find method to assign it another object for example right?

#

a private field

swift crag
ivory bobcat
swift crag
#

This is completely fine.

polar acorn
#

private and public have zero effect on any fields defined inside the same class

swift crag
#

and they also have zero bearing on the exact kinds of things you can assign into the field

#

All they do is determine which classes are allowed to see the field.

ivory bobcat
#

Simply accessors

swift crag
#

Nothing else.

ivory bobcat
lofty sequoia
#

Why does Unity default button hierarchy to have the UI text under the button with the image--so frequently it bugs out and the text ends up being rendered underneath the button's image component--which is supposed to be the background of the button

#

Unity's own documentation dictates that the BUTTON gameobject is rendered on the canvas after the childmost TEXT TMP is rendered

polar acorn
swift crag
#

You must have something else going on if the text is winding up behind the button image.

#

note that this is not a code problem, and should go in #📲┃ui-ux

lofty sequoia
#

hmmm ok, I'll check settings. Not sure which one would cause that issue

swift crag
#

why don't you show us the inspectors for your button and text objects, as well as a screenshot of the scene view showing the problem, in #📲┃ui-ux

dense root
#

How come the editor is angry with me that the faderImage isn't set to active when I'm doing it in my fadeOut function?

    public IEnumerator FadeIn()
    {
        faderImage.gameObject.SetActive(true);
    }

    public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
    {
        yield return StartCoroutine(FadeIn());
        playerTransform.position = newPosition;
        yield return StartCoroutine(FadeOut());
    }
swift crag
#

you can't start a coroutine on a MonoBehaviour whose game object is deactivated

dense root
#

Crap... so how do I mitigate this fader canvas issue? If I have it active on start it's going to block my mouse

swift crag
#

proactively activate it first

dense root
#

If I set it to active at first and then deactivate it in script I still get the same error

    void Start()
    {
        faderImage.color = new Color(0, 0, 0, 0);
        // Set Fader to inactive so that it doesn't interfere with other canvases
        faderImage.gameObject.SetActive(false);
    }
swift crag
#

since you're just calling StartCoroutine

#

that's equivalent to this.StartCoroutine(...)

stuck palm
#

every fixed update, an input packet is added to a list of input packets.

#
[Serializable]
public struct InputPacket
{
    public List<ButtonState> buttonList;
    public List<MoveState> moveList;
    public bool LTPressed;
    public bool RTPressed;
}
#

LTPressed and RTPressed are both accurately recorded, but the lists dont seem to work as expected

dense root
#

Should I explicity write out this.StartCoroutine?

polar acorn
swift crag
#

I'm just pointing out who's running the coroutine

dense root
#

oh

stuck palm
#
protected virtual void Awake()
    {
        sendRegister?.Invoke(this);
        currentInputPacket = new InputPacket();
    }

at the start, a new InputPacket is created.

wintry quarry
stuck palm
#

i just called it a packet

wintry quarry
#

ok so what isn't working as expected about the lists?

stuck palm
#

the lists just dont seem to have anything in them.

dense root
#

It's angry at the FadeIn line

    public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
    {
        yield return StartCoroutine(FadeIn());
        playerTransform.position = newPosition;
        yield return StartCoroutine(FadeOut());
    }
wintry quarry
stuck palm
#

i think its because i didnt initialise them?

stuck palm
wintry quarry
stuck palm
#
public void UpPress(InputAction.CallbackContext ctx)
    {
        if (ctx.performed)
        {
            currentInputPacket.moveList.Insert(0,MoveState.Up);
        }
        else
        {
            currentInputPacket.moveList.Remove(MoveState.Up);
        }
    }
polar acorn
wintry quarry
swift crag
#

What is that component attached to?

stuck palm
wintry quarry
swift crag
#

because---

#

yep

wintry quarry
#

and unity's serializer abhoirs null

swift crag
#

This is a fun surprise

wintry quarry
#

it creates an empty list

#

you should create the list in a constructor.

dense root
wintry quarry
#

or deal with the possibility of it being null

swift crag
#

Remember: what matters is the object your component is attached to

#

The state of the image's object is irrelevant here.

stuck palm
wintry quarry
dense root
swift crag
#

Find out by logging it.

#

Log gameObject.activeInHierarchy right before trying to start the FadeIn coroutine

dense root
#
    public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
    {
        Debug.Log("gameObject.activeInHierarchy : " + gameObject.activeInHierarchy);
        yield return StartCoroutine(FadeIn());
        playerTransform.position = newPosition;
        yield return StartCoroutine(FadeOut());
    }
swift crag
dense root
#

That's weird... I'm not deactivating the dojo AFAIK

swift crag
#

They can still contain reference types.

wintry quarry
stuck palm
wintry quarry
stuck palm
#

do i need to create a new instance of the list every time

polar acorn
stuck palm
#

are lists structs or reference types?

wintry quarry
wintry quarry
dense root
#

This is weird... gameObject.activeInHierarchy is returning false but it's active in the inspector. What the heck is happening?

wintry quarry
polar acorn
stuck palm
#

buttonList = new List<ButtonState>(packet.buttonList); when you do this, does it essentially just duplicate the contents?

wintry quarry
dense root
#

Oh here we go, I just set the faderImage to active once the coroutine is called and it solved my issue

    public IEnumerator FadeTransition(Vector3 newPosition, Transform playerTransform)
    {
        faderImage.gameObject.SetActive(true);
        yield return StartCoroutine(FadeIn());
        playerTransform.position = newPosition;
        yield return StartCoroutine(FadeOut());
    }
#

For some reason it doesn't like to be called from FadeIn

stuck palm
stuck palm
#

@swift crag tried my hand at the hash system again, this time all i did was hash the positions, and again it works for like 36 frames at the start then immediately desyncs lmao

#

but the replay itself seems to work fine until a bit longer

mild onyx
#

how would i make my sprite only jump once (Input.GetKeyDown(KeyCode.Space) == true) makes it fly

ivory bobcat
mild onyx
wintry quarry
ivory bobcat
#

GetKeyDown only occurs once

mild onyx
#

i got this

ivory bobcat