#💻┃code-beginner

1 messages · Page 810 of 1

naive pawn
#

make it

frigid lark
#

thats what im asking, i dont know where to start

naive pawn
#

(that was in reply to buddy)

frigid lark
#

mb

naive pawn
#

btw on that "limit diagonal running", you generally would not have to do that, just normalize or clampvelocity on the input and then limit the overall magnitude of the speed

frigid lark
#

yeah

#

well i cant use vector3.clampmagnitude becuase that would also affect the y axis

#

but yeah its a little rough around the edges ill clean it up a bit

naive pawn
#

you can clamp magnitude on the input before applying it to the rb

frigid lark
#

i know..

naive pawn
#

are you sure the loss of momentum is due to CounterMovement?

#

nothing there changes when you hit the ground

frigid lark
#

it might be, its hard to tell

naive pawn
#

i feel like it's just due to ground friction

frigid lark
#

because when i dont have if(grounded) return; the player accelerates so fast in air to the point where i think it just negates the halting

frigid lark
naive pawn
cunning rapids
#

Btw that's what dani does too

#

Physics material --> 0 fric

frigid lark
naive pawn
frigid lark
#

im realising now i forgot to do it lol

cunning rapids
#

In what way? Like it decelerates instead of abruptly stopping?

naive pawn
#

adding or removing if (grounded) return; affects the behavior on the ground. it wouldn't change the behavior in the air, assuming the grounded check was written properly

frigid lark
# naive pawn what about it

like at the start of CounterMovement() i would have if(grounded) return; then it wouldnt counter movement in air

naive pawn
frigid lark
#

wdym

frigid lark
naive pawn
frigid lark
#

i missed it mb

#

sorry, i mean !grounded return

#

its been a long day man sorry

naive pawn
#

(might want to consider noting down where you left off and taking a break then)

frigid lark
#

nah its just school i havent actually been doing much gamedev today. about 30mins-1hr

#

maybe its the extra gravity

#

because if im constantly applying a downward force then its going to try and push me into the ground

#

and maybe thats stopping it

naive pawn
#

shouldn't affect anything with no friction

frigid lark
#

oh true

#

yeah didnt do anything ;-;

naive pawn
#

does the loss of momentum happen if you just comment out the CounterMovement call entirely?

frigid lark
#

checking

#

yeah it does

#

but then i slip and slide like a penguini

#

and increasing friction would just reintroduce the problem, would it not?

naive pawn
#

oh yeah this wasn't a solution, just a check to see if CounterMovement was the cause

#

and, well, clearly not

ivory bobcat
#
private float previous;```
ruby python
#

!code

radiant voidBOT
ruby python
#

Hi all, I'm having a bit of a brainfart.

            if (GameManager.Instance.globalDataManager.closestStargate.GetComponentInParent<GroundTileDataContainer>().groundTileBiomeData.canShowFootprints == true)
            {
                GameObject newFootstep = footprintPool.GetPooledObject();
                newFootstep.transform.position = new Vector3(
                    transform.position.x,
                    0.01f,
                    transform.position.z);

                newFootstep.transform.rotation = Quaternion.Euler(
                    0,
                    playerGameObject.transform.rotation.y,
                    0);
                newFootstep.SetActive(true);
                Debug.Log("Should be Footprint");
                StartCoroutine(DisableFootstep(newFootstep));
            }

I'm grabbing some footprints from my pool and they're working great, except for the rotation, I can't seem to figure it out (they always enable with a Y rotation of 0. Can anyone see where I'm going wrong please? 😕

celest depot
#

Hello. Im new to Unity 6.3, and I faced this kind of problem.

error CS0246: The type or namespace name 'MaterialReferenceChanger' could not be found (are you missing a using directive or an assembly reference?)

How do i fix this? I did try to find the solution through YT, Google and Grok AI, but I still don't understand.

ivory bobcat
ivory bobcat
ivory bobcat
ruby python
ruby python
#

Thanks:)

#

Yep, that fixed it. lol.

celest depot
#

the very first line, but i could not find the error.

ivory bobcat
#

I want to see the console window to better evaluate the stack and error.

celest depot
#

wait

ivory bobcat
#

To open the Console, from Unity’s main menu go to Window > General > Console.

ivory bobcat
# celest depot

Try restarting the Unity Editor. It may be a false positive.

celest depot
#

How?

ivory bobcat
#

Close the Unity Editor application and launch the project again from the Unity Hub.

celest depot
#

You mean delete the 6.3 editor and install back?

ivory bobcat
#

No. Close the Unity Editor. Then open the project again from your Unity Hub.

celest depot
#

Ok

boreal vine
#

Hi guys I got a problem, when I run my 2D game. I think there should be way to disable unity short controls, when code running like control + p (stop running), because in my game parry is leftControl and attack "p". Thank you for help!

celest depot
midnight plover
celest depot
midnight plover
livid anchor
#

If I want an object to strafe left and right in a smooth manner, what are my options ? I'm looking at Vector3.MoveTowards but it needs to be in an update apparently. Can I do a movement by trasform outside the update ?

midnight plover
livid anchor
#

What I'm trying to do is : I have the input reference action for movement (left and right arrows), I put an event on action.performed and from that I want to do a smooth movement to a fixed position, like go from x = 0 to x = 3

midnight plover
#

so to make it smooth, transform.position = vector3.lerp or whatever you want to smooth in update and in your callback method, update the actual targetvector

livid anchor
#

I think I understand. The event just set a target and the update follow it

fallen snow
#

Hey, so I have a character controller. Currently, I use rigidbody's drag float to increase drag while the character is grounded. unfortunately this is causing issues with my dash feature. The dash feature is meant to set the drag do zero while dashing (which it does) but for some reason if I set grounded drag to 0 instead, the dash is much cleaner.

Basically my question is, is there a better way than creating counter force or increasing rigidbody drag while grounded to give a tighter less floaty physics based movement controller?

scarlet hemlock
#

Hi I'm trying to understand the new unity Input system I'm Following the Unity Input System in Unity 6 (2/7): Input System Scripting Video and im trying to understand something We used to use The X and Z axis for movement in vector 3 but now we use Y axis in a vector 2 from the action maps. Doesn't Y normally refer to Up in the world?

midnight plover
midnight plover
fallen snow
# midnight plover Dashing sounds to me like it should not be "dragged influenced", or? So setting ...

yeah, that's what I have currently. I must have messed it up though. I see in the inspector it does set drag to 0 on the rigidbody when I dash. but dash works so much better mid air where the drag is set to 1 than on land where it's set to 8 despite the fact that drag should be set to 0 while dashing and that seems to actually be the case too. Hmm maybe it's some sort of string tension thing because I made my capsule controller hover with spring force...

sour fulcrum
scarlet hemlock
#

and y refers to w and s

midnight plover
sour fulcrum
#

what x, y and z "mean" is defined on how those values are being used in the given situation

#

they don't have an overarching definition that spans every usecase

midnight plover
#

commonly used: x,y = left/right, up/down (in input case)

sour fulcrum
#

eg. you might use a Vector2 to conveniently store a minimum and maximum value, which would be using x and y

#

purely because its nice to store them as a pair of two numbers

fallen snow
midnight plover
scarlet hemlock
livid anchor
#

Hmm I have an issue... i'm trying to make strafe movements in a sort of rigid way, and I'm using fixed value for that. Like I consider my starting point to be (0,1,0) and I want to move in (3,1,0). The issue is I also want to jump so I ut a rigid body, but now my position is weird, I don't have clean values like 0 or 3

midnight plover
livid anchor
#

Well the game is supposed to be a kind of infinite runner. I have a character that can strafe on three "roads" and jump. I thought that transform.position to move left and right would fit. Since I need to just go from one point to the other

midnight plover
livid anchor
#

That's indeed an issue

midnight plover
livid anchor
#

in a fixed update right ?

midnight plover
livid anchor
#

Now that I think about it I can see a problem arising. The character is supposed to be able to fly also... I fear the time when I'll have to deal with that and gravity

#

or maybe I can disable gravity when I fly?

midnight plover
quartz geyser
#

can anyone tell me the best place to learn coding for games... like i dont want any of that 'hello world' starter bs
i want coding which will be for games mainly for 3D

solar hill
#

!learn

radiant voidBOT
livid anchor
#

Ok basic movement done. I just need to make an imput buffer for more smoothness in the controls

livid anchor
#

I'm thinking about how to make an input buffer. My thought so far is to save the command the player enter, create a list of command that is limited in size (like two or three inputs at a time) and then in the update, if you're available to do an action, you pick the first entry and do that.

Am I right ?

subtle mulch
#

it might create more problems that it solves

balmy vortex
#

hi would Vector3.Reflect() work for something like a projectile parry?

#

or is there some better way of implementing that?

lethal meadow
balmy vortex
#

ya

lethal meadow
pseudo jackal
#

How do I set up adaptive ui, my ui is messed up for some devices, pls help

lethal meadow
livid anchor
livid anchor
#

Helps with the controls

livid anchor
subtle mulch
#

well, let's say you are still in air

lethal meadow
subtle mulch
#

and press jump

#

well, then you would jump when you land even if you now don't want to

#

if you want to use a buffer, then maybe make the command inside expire after 1s or 0.5s

livid anchor
lethal meadow
#

gotta be ragebait

subtle mulch
#

still, make the buffer expire after 1s or 0.5s

balmy vortex
#

what's actually the difference between Physics.OverlapSphere and Physics.OverlapSphereNonAlloc?

elfin pike
#

what im doing wrong. cant find. ```Action<InputAction.CallbackContext> _action;
void ActivateRuneInput()
{
_action = ctx => HandleRuneSlotInput(0);
runeSlotInputs[0].action.performed += _action;
}

void OnDestroy()
{
    runeSlotInputs[0].action.performed -= _action;
}
subtle mulch
#

we are not mind readers

elfin pike
subtle mulch
#

maybe this helps?

#

tho i think it's what you are doing, hmm

#

are you sure the subscribe function is getting called?

elfin pike
#
  1. It subs, but doesnt calls function
  2. It doesnt Unsub
subtle mulch
#

are you destroying the object?

elfin pike
subtle mulch
#

put a debug there

#

and check if it's getting called

elfin pike
#

i know that it gets destroyed. i have done it million timess

subtle mulch
#

bc if it subscribes, then 100% it's caling that function

subtle mulch
#

same for the action

#

add another function to the subscribed ones

#

where it's just a debug

#

to check if the action is actually getting performed

elfin pike
#

Action, performed.
Function not called.
OnDestroy called

subtle mulch
#

ok that's strange

subtle mulch
#

try this

#

did it work?

elfin pike
#

no

subtle mulch
#

ok that's very strange

#

can you send the full code please

elfin pike
#

its too long to send

subtle mulch
#

send the file

elfin pike
#
[SerializeField] InputActionReference[] runeSlotInputs = new InputActionReference[10];
int selectedSlotIndex = 0;
List<BlockType> blockTypesOrder = new List<BlockType>(); // To store the order of block types
EventSystem eventSystem;
Action<InputAction.CallbackContext> _action;

void ActivateRuneInput()
{
    runeSlotInputs[0].action.performed += OnRunePerformed;
}

void OnDestroy()
{
    runeSlotInputs[0].action.performed -= OnRunePerformed;

    BlockSlot.OnSlotClicked -= HandleSlotClicked;

    if (LoadoutList == null || LoadoutList.Count == 0)
    {
        Debug.LogWarning("LoadoutList is not initialized or empty. Skipping SaveLoadoutList.");
        return;
    }

    SaveLoadoutList();
}

void HandleSlotClicked(int slotIndex)
{
    selectedSlotIndex = slotIndex;
}
    
private void OnRunePerformed(InputAction.CallbackContext ctx)
{
    HandleRuneSlotInput(0);
}

void HandleRuneSlotInput(int index)
{
    //For setting selectedIndex to clicked slot.
    BlockSlot selectedObject = EventSystem.current.currentSelectedGameObject.GetComponent<BlockSlot>();
    if(selectedObject)
    {
        selectedSlotIndex = LoadoutList.FindIndex(slot => slot == selectedObject);
    }
    else return;

    Debug.Log($"Index: {index}, Selected Slot Index: {selectedSlotIndex}");
    LoadoutList[selectedSlotIndex].SetRune(blockTypesOrder[index]);
    selectedSlotIndex = (++selectedSlotIndex) % LoadoutList.Count;

    //Sets selected slot
    if (eventSystem != null)
    {
        var baseEventData = new BaseEventData(eventSystem);
        eventSystem.SetSelectedGameObject(LoadoutList[selectedSlotIndex].gameObject, baseEventData);
    }
}```
#

took all related functions and variables

subtle mulch
#

void OnEnable()
{
if (runeSlotInputs[0]?.action != null)
{
runeSlotInputs[0].action.Enable();
runeSlotInputs[0].action.performed += OnRunePerformed;
}
BlockSlot.OnSlotClicked += HandleSlotClicked;
}

void OnDisable()
{
if (runeSlotInputs[0]?.action != null)
{
runeSlotInputs[0].action.performed -= OnRunePerformed;
runeSlotInputs[0].action.Disable();
}
BlockSlot.OnSlotClicked -= HandleSlotClicked;
}

#

instead of OnDestroy and your function

#

tho you can keep using those if you want

elfin pike
#

lol worked. now i have to make for loop to enable certain count of actions

slender kelp
#

guys can u guys help i dont understand the curly bracket thingys

elfin pike
#

so, i got stuck. private void OnRunePerformed(InputAction.CallbackContext ctx, int i) { HandleRuneSlotInput(i); }how do you give it extra values? Or i have to create for each action its own function

slender kelp
naive pawn
subtle mulch
elfin pike
subtle mulch
#

prob

rich adder
#

Is this a troll post?..

subtle mulch
#

or lua

naive pawn
#

i mean i could totally see this being about properties but not describing it well, i'm giving them the benefit of the doubt

elfin pike
subtle mulch
#

for (int i = 0; i < runeSlotInputs.Length; i++)
{
var actionRef = runeSlotInputs[i];
if (actionRef?.action == null) continue;

    int index = i; // Capture current i
    _runeActions[i] = ctx => HandleRuneSlotInput(index);
    actionRef.action.performed += _runeActions[i];
    actionRef.action.Enable();
}
#

to subscribe

#

for (int i = 0; i < runeSlotInputs.Length; i++)
{
var actionRef = runeSlotInputs[i];
if (actionRef?.action == null || _runeActions[i] == null) continue;

    actionRef.action.performed -= _runeActions[i];
    actionRef.action.Disable();
}
#

to unsubscribe

slender kelp
#

nah its alr i fixed it

subtle mulch
slender kelp
subtle mulch
#

huh?

#

{ opens a piece of code

#

} closes it

#

it's not that hard

slender kelp
subtle mulch
#

wdym designers...

slender kelp
slender kelp
subtle mulch
#

ppl?

slender kelp
#

yes

subtle mulch
#

!collab prob

radiant voidBOT
# subtle mulch !collab prob

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**

subtle mulch
#

tho don't expect them to work for free

slender kelp
#

oh thanks

#

my paypal is frozen tho

subtle mulch
#

huuh, well, gl then

#

paypal is not the only method btw

#

(it's also the worst, but let's not go down that rabbit hole)

slender kelp
#

ok

sterile sandal
#

Can I get help from a good developer?

frosty hound
#

You need to ask a question first

copper sonnet
#

idk if this is the right place to ask but i need help learning how to script

frosty hound
#

!learn is a good place to start for general Unity/coding for beginners.

radiant voidBOT
copper sonnet
#

thank you

sour fulcrum
#

this is probably a "try it and see" but if i wanna cast a ienumerable like this can i do it like this directly or do i need to make a new one and add a casted version of each element

    public void AddListener(Action<IEnumerable<T>> action)
    {
        MultiColumn.selectionChanged += (e) => action.Invoke(e as IEnumerable<T>);
    }
#

oh do i just pop a linq cast?

naive pawn
#

IEnumerable<string> and IEnumerable<object> are related, but List<string> and List<object> are not - at least as far as i understand (which may well be wrong)

sour fulcrum
#

Rubber ducked myself, the code snippet doesn't work in the sense that the casted ienumerable is valid but the contents seem to be wiped

#

Linq's .Cast<T> just works

#

ty

sour fulcrum
#

I guess this is more of a c# question than Unity but is there a standard convention to mark in a DateTime (or equivalent) that a part of the date is unknown / invalid? or do i need my own solution for this

#

i have stuff where some things have a fully known date (eg. 05/09/2014) but also things that only have a partial (eg. ??/04/2012)

naive pawn
#

the canonical way to store datetimes are either unix or iso 8601 timestamps, so i guess you could technically use the latter but you'd have to process a lot yourself

so this probably would not be a built-in thing

sour fulcrum
#

scary words, fair enough thanks

#

dont mind cooking something up was just curious what the proper route was 😄 ty again

solar hill
#

let me see if i can find the one im thinking off

wintry quarry
#

or use a separate "mask"

sour fulcrum
wintry quarry
#

for marking which parts are known/unknown

#

(which is essentially a custom data type)_

#

that's probably the best way tbh - the mask

sour fulcrum
#

this is on a project to learn ui toolkit so a custom data type is a good excuse to learn how to make a nice drawer for it

worldly mural
#

i made a movement script and a 1st person camera controller script, but for some reason when im moving and turning my camera at the same time, its very jittery, any ideas how to fix this?

cosmic quail
naive pawn
#

and make sure you aren't modifying the transform of an object that has an rb

worldly mural
worldly mural
cosmic quail
#

or use addforce, that works too i guess

worldly mural
#

both of those work with the new unity input system right?

worldly mural
#

alright thanks

naive pawn
worldly mural
#

ah okay

vagrant reef
#

what is the line to switch scenes?

wintry quarry
#

Google Unity SceneManager

#

There's no one "line". All the methods to load scenes are in that class though

vagrant reef
#

Assets\Scripts\MenuLogicScript.cs(1,19): error CS0234: The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

using UnityEngine.SceneManagement;

public class MenuLogicScript : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

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

    public void SwitchScenes()
    {
        SceneManager.LoadScene(1);
    }

    public void Exit()
    {
        Application.Quit();
    }
}
slender nymph
#

if the error is coming from that code then you haven't saved it after making the change from UnityEditor to UnityEngine

vagrant reef
#

and the code works

#

that error only appears when i try to build

slender nymph
#

then you are looking in the wrong file

#

or you've copied everything after the first line since the error appears on line 1

vagrant reef
#

yea I had the same using UnityEngine.SceneManagement; twice

#

I removed it before I sent it

slender nymph
#

are you sure the first one wasn't the UnityEditor.SceneManagement line? because that one would be the exact one that was causing the error since the editor assembly doesn't exist in a build

slender nymph
#

and for future reference, do not modify the code when sending it when you are experiencing errors

vagrant reef
#

Ima save and try to build again

polar acorn
vagrant reef
#

it works now

polar acorn
#

So, you almost certainly had both, and when you removed the "duplicate" by posting it here you actually fixed the error

vagrant reef
#

thanks yall ❤️

rough sluice
#

Can we get Unity documentation as PDF?

ruby surge
#

Hello! Super noob here, how come my VS code isn't autofilling? In the tutorial for essentials, I'm on the step where we have to add the OnTriggerEnter.

When I start to Type On, that option doesn't appear.

I have C# and C# Dev Kit entension installed

solar hill
#

!ide

radiant voidBOT
fallen mural
#

can anyone help with this? for some reason my vscode randomly decided to stop showing syntax highlighting for unity and its really inconvenient (since im new and it gives you descriptions of what each field does)

#

ive tried regenerating project files, checking for vscode updates and reinstalling the unity extension on vscode

#

(if you wait a bit into the video you can see that it initially knows what to highlight then decides to not do it)

solar hill
fallen mural
#

I did, I tried doing those steps already

#

The problem doesn't fix

ivory bobcat
solar hill
#

oh yeah its not reading your .slnx

#

you have to install a new .net version

dreamy nexus
#

Heyy SUPER new noob question. I'm trying to learn about different joints and I'm watching a youtube tutorial for it. In the video the guy sets up a fixed joint with one cube connecting to another one. With the fixed joint, he's able to grab and drag one of the cubes to make them both move.

When I added the fixed joint, I am not able to make the both move, but when I got to play mode I can see the cubes fixed and hovering. How is he able to make these physics active while in Scene view?

dreamy nexus
west rain
#

Hey everyone. I have a homing projectile in my scene that is supposed to fly to my player

    Vector2 direction = (player.position - transform.position).normalized;
    rBody.linearVelocity  = direction * homingSpeed;

but for some reason this isn't running. What might be causing this? the gravity scale for the object is 0 as well

teal viper
polar acorn
#

And make sure you're not immediately overwriting the linear velocity next frame

wintry quarry
west rain
polar acorn
#

If the debug from the line before is printing, then this code is running

west rain
#

i mean yeah but they are not flying to my player 😂

solar hill
#

are they flying anywhere?

#

does player.position have a reference to the player?

west rain
#

nope. just sitting as they were right before their gravity is reduced to 0

#

player = GameObject.FindGameObjectWithTag("Player").transform;

yeah it has this

solar hill
#

where is the original code snippet located'

west rain
#

its in the prefab itself

#

its a gem collectible

solar hill
#

i meant within your code

#

is it in your update function?

west rain
#

in the update loop

#

yeah

solar hill
#

log your player.position and direction values right after the code snippet and show what the console says

west rain
#

1 sec

#

it shows UnityEngine.transform for player.transform

#

is that the issue

solar hill
#

log the values.

west rain
#

Debug.Log($"{player.transform} Going to Player");

im doing this. dont really know how to log values

polar acorn
west rain
solar hill
#

log player.position

teal viper
#

At this point you should inspect the projectile object at runtime and share screenshots with us to avoid playing a guessing game.

#

As well as print the linear velocity and tell us the value.

west rain
polar acorn
west rain
#

since the gems are spawned after start, i tried moving
player = GameObject.FindGameObjectWithTag("Player").transform;
this to update but it didnt help either

teal viper
#

Not a screenshot of code.

west rain
#

assigned in parent class collectible

polar acorn
#

What is it assigned to? How is it assigned?

west rain
teal viper
#

A screenshot of the projectile inspector at runtime please...

solar hill
#

but at this point i doubt it matters

#

this also might be a long shot but have you confirmed your Player has the Player tag?

west rain
west rain
solar hill
#

then open the prefab

teal viper
sour fulcrum
west rain
#

changed the log to transform as well

teal viper
#

I bet the animator is the culprit.

polar acorn
#

We still don't know what rBody is referring to

west rain
#

its refering to the Rigidbody2D

teal viper
#

Also, when taking a screenshot like that, make sure rigidbody is visible too.

polar acorn
#

How is it assigned

west rain
#

ill try without animator

west rain
polar acorn
# west rain I assigned it 😂 wdym

Okay, this is what I wanted. rBody could easily have been accidentally assigned to the prefab instead of this instance which would mean you wouldn't see any changes.

west rain
#

i think it cant find the player for some reason

solar hill
#

I doubt since your log worked

polar acorn
#

If it couldn't find the player, you would be seeing errors from trying to refer to player

solar hill
#

is your Collectible script also on the gems?

west rain
#

gem is inheriting from collectible so yes

teal viper
#

Does the animator running an animation that modifies the object position?

west rain
slender nymph
#

when you say "without animation" do you mean you disabled the animator, removed it, or did something else?

west rain
#

removed the part with the object modification part

slender nymph
#

i don't know what you mean by that either

polar acorn
#

Change your log to this:

Debug.Log($"{gameObject.name}'s Rigidbody {rBody.gameObject.name} is moving from {transform.position} to {player.position} with a speed of {homingSpeed}");
teal viper
#

And a screenshot of the rb at runtime.

west rain
solar hill
#

it could be that since they are moving towards the ground check, they arent moving because they are actually dragging across the floors due to the colliders

#

since the ground check would be below their own transform point

polar acorn
# west rain

Well, it's got at least 2500 units to cover at a speed of 5 units per second so that's gonna be a while

slender nymph
#

oh god, was everything scaled up to match the canvas size or something

teal viper
#

Some of them are close though

solar hill
#

yeah some are close

teal viper
#

It's probably other gems far away

west rain
#

yeah those are the ones that fall while gravity is activated

solar hill
#

i still like my theory 😊

west rain
#

other gems far away dont get activated

teal viper
#

I bet on kuzmo's guess.

polar acorn
#

Might be good for testing to only spawn one

west rain
#

they arent dragging across the floor cuz then they'd move when i jump

solar hill
#

fair that debunks that i guess

#

does changing the speed value to something massive like 500 have any effect?

west rain
#

just did and it didnt

#

ill replace animator with a sprite renderer and try

teal viper
#

I guess what's left is to have a look at the parent object.

solar hill
#

was about to say

#

does the parent object have any scripts on it?

teal viper
west rain
#

i did

#

still nothing

teal viper
#

OK, then the parent. As well as bumping the speed to a high value.

solar hill
west rain
#

it doesnt

#

but i think i found the issue

#

rigidbody is turning static for some reason

#

its not static at runtime or when spawned. Idk what that'd happen

teal viper
#

When does it turn static? I don't see it on the screenshot.

west rain
#

when i have the animator turned off

#

it didnt when i ran it this time tho. Im so lost

teal viper
#

Try making it dynamic at runtime and see if it moves.

solar hill
#

if all else fails, grab a direct serialized reference to your rigibody in the gem script

#

and try that

west rain
#

it somewhat worked when i reactivated the animator

#

the gems didnt move since they have an object transform. but they played the picked up sound. Their speed is set to 500 so i think in the update, their rbody went to the play while the sprite stayed still

teal viper
#

How did the sprite stay behind if it's on the same object?

west rain
#

i think its an update bug

teal viper
#

I really doubt that.

solar hill
#

does the parent also have a sprite renderer?

teal viper
#

That's more likely

solar hill
#

what does the parent object have

#

also expand your spriterenderer in the inspector and screenshot it

west rain
#

it has its own rigidbody and boxcollider

#

this is the sprite renderer

solar hill
#

screenshot the parents inspector

west rain
solar hill
#

what happens if you disable both on the parent

west rain
#

i think they fall straight down and come back to the player after gravity is set to 0

solar hill
#

my question is why is this even 2 gameobjects at all? I think you should remake the gem prefab imo, keep the rb and colliders only on the parent, and use the child for the sprite and animator

west rain
#

i know thats kind of a problem. I tried doing it that way. It basically has a pickup animation that also runs functions with events on the animator

wintry quarry
# west rain

yeah you absolutely don't want a separate rigidbody on the parent and child

#

the rigidbody should be on the parent, and there should only be one

#

the collider can live on either - doesn't matter which

west rain
#

ill try changing it at this point

wintry quarry
#

Separate rigidbody == separate physics object

west rain
#

👍 thank you all for your time. I know its bad coding and practice but i didnt really know what the issue was when we began notlikethis

polar acorn
solar hill
#

only the child has a sprite it seems, but yeah i dont see the point in 2 colliders and 2 rigidbodies

steep sage
#

can som help

slender nymph
#

!ask
-# inb4 "gtag fangame"

radiant voidBOT
# slender nymph !ask -# inb4 "gtag fangame"

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #🌱┃start-here

true owl
#

hey guys im having some difficult figuring out how to make this momentum system work the Y
I want it such that when a player hits a wall while sliding it retains a bit of their momentum and makes them slide, but I see the issue right now is the rb.linearVelocityY has basically infinite addition to itself. I'm not really sure how to make it return to its "default" state of having the physics control it
https://pastebin.com/LGvE4X29

thick sedge
#

hi, can I ask a question here because idk what channel to post it at?

#

anyways changing any value on the Global light 2D URP doesn't do anything, any suggestions?:D

hidden fossil
#

running into some issue where i dont know why but it enters isshooting bool and never turns it off

#
using UnityEngine.InputSystem;

public class Player_Bow : MonoBehaviour
{
    [SerializeField] private Transform launchPoint;
    [SerializeField] private GameObject arrowPrefab;
    [SerializeField] private float shootCooldown = 0.5f;
    private Player_Movement playerMovement;
    [SerializeField] private float shootTimer;
    private Animator anim;
    private Vector2 aimDirection = Vector2.right;

    private void Awake()
    {
        playerMovement = GetComponent<Player_Movement>();
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        shootTimer -= Time.deltaTime;

        HandleAiming();

        if (Keyboard.current.fKey.wasPressedThisFrame && shootTimer <= 0)
        {
            print("F clicked!");
            playerMovement.isShooting = true;
            anim.SetBool("isShooting", true);
        }
    }

    private void OnEnable()
    {
        anim.SetLayerWeight(0, 0);
        anim.SetLayerWeight(1, 1);
    }

    private void OnDisable()
    {
        anim.SetLayerWeight(0, 1);
        anim.SetLayerWeight(1, 0);
    }

    private void HandleAiming()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        if (horizontal != 0 || vertical != 0)
        {
            aimDirection = new Vector2(horizontal, vertical).normalized;
            anim.SetFloat("aimX", aimDirection.x);
            anim.SetFloat("aimY", aimDirection.y);
        }
    }

    public void Shoot()
    {
        if (shootTimer <= 0)
        {   
            Arrow arrow = Instantiate(arrowPrefab, launchPoint.position, Quaternion.identity).GetComponent<Arrow>();
            arrow.direction = aimDirection;
            shootTimer = shootCooldown;
            print("Fired an arrow!");
        }

        anim.SetBool("isShooting", false);
        playerMovement.isShooting = false;
    }
}```
slender nymph
#

you set it to false in the Shoot method, but where do you actually call that?

hidden fossil
wintry quarry
solar hill
#

or what

hidden fossil
solar hill
#

that is very backwards

hidden fossil
solar hill
#

but why

hidden fossil
solar hill
#

why do it this way... you can just call the shoot function when you press F

#

and then set the bool there

hidden fossil
#

it shoots right away

#

i want to make it shoot on a certain frame

#

not right away

solar hill
#

are you positive your Shoot function is getting called at all?

hidden fossil
#

how would it be set to true if its not being called

wintry quarry
solar hill
hidden fossil
#

oh

solar hill
#

i dont think your shoot function is being called at all

#

this is also why i recommended what i did earlier

#

keep the shooting mechanics under 1 function

#

if you need it delayed with an animation event keep that as a seperate function

#

then in your update just do "if (f) Shoot();"

hidden fossil
#

like this?

solar hill
#

put playerMovement.isShooting under that function as well

hidden fossil
#

oh wait

#

i just realized my error

#

my animation isnt even playing

#

ah

#

finally found the issue after 2 days

crimson gorge
#

This intellisense thing is an insane asf mind reader/ predictor or my codes are just that simple?

naive pawn
#

it sounds like you're talking about intellicode

#

but probably the latter

harsh rain
#

Hi all! I'm a newcomer to DOTS and ECS and I'm running into a problem, and I was wondering if anyone here might have any advice?

Is it possible to gain read-write access to a DynamicBuffer during a parallel job without passing it in as a parameter? I have a parent entity that the job operates on, but during the logic, I need to alter a DynamicBuffer belonging to a child entity of that parent.

Unity's built-in safety systems are preventing me from using a BufferLookup with read-write permission in a parallel job to prevent multiple threads from trying to write to the buffer simultaneously, but I believe that each individual child's DynamicBuffer will only be accessed once, so unless I'm mistaken there shouldn't be a risk of that happening.

I'm unfamiliar with other ways to access a DynamicBuffer of a different entity other than a BufferLookup, and my attempts at searching and asking so far have not led me to figuring out how to remedy this or work around it. Any assistance is appreciated!

teal viper
harsh rain
celest depot
#

Hello guys, I tried to code a yaw movement to my object, but it kinda buggy. Can anyone detect my error? I want to code the object to do yaw movement without any problems.

midnight plover
radiant voidBOT
naive pawn
#

!ide

radiant voidBOT
forest cosmos
#

Hey, my IDE just stopped working and m confused whats going on.
I have .net 8 and 9 installed. It was working fine, but today VSCode is saying this.
You must install or update .NET to run this application.
Framework: Microsoft.NETCore.App version 10.0.0

#

I dont have C# Dev kit

#

just C# and .net install in vscode

#

When i open VSCode, I get this error.

naive pawn
#

are your extensions and ide version all up to date?

regal ice
#

hey, i was wondering whether there is a way to modify this .lua file inside the resources.assets in the files of a game? I dont know where to ask this kind of question

#

i tried to open the file with unity, but it didnt work, im really unexperienced but trying to mod some parts of the game "Esports Club"

midnight plover
forest cosmos
#

I installed .net 10 and its working now.

regal ice
#

i tried to google, the game only has a chinese playerbase and sadly i dont know any chinese

midnight plover
lunar axle
#

how can i change Debug.Log() text color?

rich adder
lunar axle
lunar axle
scenic iris
#

i try to learn how .json works because i need to save and load some data on my game.

i already have the json file but i haven't figured how to add thos value to load on my code as veritable if found this i will move next part is to save values back but first i have to found how to make out load the data for json.

{
  "playerName": "David",
  "isAlive": true,
  "score": 150
}
scenic iris
midnight plover
rich adder
scenic iris
#

so beastly like this ?

    public string playerName;
    public bool isAlive;
    public int score;


rich adder
#

Pretty much

scenic iris
#

yes but how to make this value to take the json data for example in this case player name becomes David or whatever value i have ?

midnight plover
#

so if you wanted to change the name, you take your c# object, set the value and serialize it to json and save that string to some file on your harddrive/playerprefs/whatever you like

scenic iris
#

i already have the json file i don't know how to load this to my script.

midnight plover
rich adder
rocky canyon
#

formattedMsg = $"<color={color}>{formattedMsg}</color>";

lunar axle
rocky canyon
#

very welcome... it was kind of a "just bored" project.. i didn't do much w/ it besides make some simple gizmos i can use like circles and rays and whatnot

#

but ur welcome to any of it that helps u out @lunar axle 🍀 happy coding

lunar axle
#

like i can wrap the styles to a struct which will be cleaner

#

although this is already good enough

scenic iris
rocky canyon
#

Serialization and deserialization are the steps that let your code go back and forth between objects and JSON

scenic iris
#

yes it make sense i haven't understood how yet to do that yet i will check the video later.
and hopefully i will understand.

low copper
#

I just read the following statement "Stay away from OnDestroy() in general: it has too many edge cases, especially at edit time. Use OnEnable() and OnDisable() for all sub / unsub needs." Does this actually make senes as a rule of thumb? I've been using it a fair amount. I definitely track the state of my objects though.

lunar axle
low copper
#

Just trying to learn best practices...I'm still very new to Unity

scenic iris
#

look i don't know what you make but some times
if you make game you have to destroy and create new game object

instead off disabled and enable but it depends on the project and the code

lunar axle
#

i think it really depends on what ur trying to achieve

rocky canyon
#

OnDisable() is called just before OnDestroy()
and OnEnable() is called before Start()

#

so its tomato tomato. like Lam said.. it depends on what u want to achieve

#

i prefer OnEnable and OnDisable.. b/c i know it'll work if im toggling the gameobject..

low copper
#

I think the "issue" is OnDestroy doesn't always run when you expect it to. In this case I'm just subscribing/unsubscribing to event actions.

rocky canyon
#

or if im destroying or instantiating

#

both work

low copper
#

I definitely create/destroy/enable/disable objects constantly

rocky canyon
#

😄 dont we all

lunar axle
rocky canyon
#

Multiple Calls: OnEnable can run multiple times, whereas Start is guaranteed to run only once per object. this is basically the idea

#

this is the caveat u have to entertain

rocky canyon
#

👍 also true.. Once per lifetime of the script instance

lunar axle
#

although i think theres a fuction call that calls even before Awake()

rocky canyon
rocky canyon
low copper
#

I've never had any issues...it was just a statement I stumbled upon. Maybe i has something to do with OnDestroy running at the end of the Script lifecycle....so people assume it might run earlier than expected

low copper
#

lol

#

I literally had the page up too

#

haha

rocky canyon
#

i had to see what dude was talkin about

#

Reset().. yea idk about him

#

never used em

scenic iris
#

spiking off create objects for what i have seen some people use method call pool

but for what i understand this system only disabled and enable those instead off destroy them and re usethem if reach then number before the do why is thhat ?

rocky canyon
#

creation takes more than if it already exists

#

pooling systems take advantage of cycling thru gameobjects that you only need to instatiate once.. (like at the beginning of the game)

#

instead of destroy and creating it just toggles on and off.. keeps the garbage collection down

#

more performant

#

you typically use just enough

#

say u only ever want 10 bullets on screen.. u'd make a collection of just 10..

#

maybe 1 or 2 more just in case

scenic iris
#

yes i knew that but hear what is the problem if make poll off 100 for example when player fire and the player doesn't fire at all this 100 object pre load with out reason even if those are disabled.

rocky canyon
#

if u dont do that you'd use a dynamic system

#

which i think is what ur talkin about..

so u create objects when needed..

#

but only up to the limit.. and then u start re-using..

lunar axle
rocky canyon
#

If player fires:

  • If disabled object exists → reuse
  • Else if CurrentPool < MaxPoolSize → create new → add to pool
#

Preloading too much is a memory/performance hit if the objects may never be used.```
#

its a balancing act..

#

as much of development is

lunar axle
rocky canyon
#

lol.. ive been learning unity 5 years now..

#

i still havent sat down and started focusing on frame-rates

#

😬 eeek lol

scenic iris
#

what im try to mix approach it will be better why at lest for my project that have multiple weapon.

intense object if object go bigger then and haven't distory reuse the existing object else if x amount time past distory or something like that

rocky canyon
#

cap it at 60 and call it a day//

lunar axle
rocky canyon
#

dont tel me theres another one 👀

#

lol

#

i dont do well in rabbit holes

lunar axle
#

Thats a good thing, u dont go too deep

rocky canyon
#

im erratic enough as is.. i have to stay really surface level to keep my sanity intact

rocky canyon
# scenic iris what im try to mix approach it will be better why at lest for my project that ha...
/// SPΔWN[CAMPGAMES]™
/// DYNAMIC OBJECT POOL || RUNTIME
/// SCRAP (scripts-development)
/// License: CC0 SpawnCampGames Free-Use, see: LICENSE.md

using UnityEngine;
using System.Collections.Generic;

public class DynamicPool : MonoBehaviour
{
    [Header("Pool Settings")]
    public GameObject prefab;       // object to pool (bullet, enemy, etc.)
    public int maxPoolSize = 10;    // max objects to ever create

    private List<GameObject> pool = new List<GameObject>();

    /// Get an object from the pool
    public GameObject GetObject()
    {
        // Look for a disabled object to reuse
        foreach (var obj in pool)
        {
            if (!obj.activeInHierarchy)
            {
                obj.SetActive(true);
                return obj;
            }
        }

        // No disabled object found, create new if under maxPoolSize
        if (pool.Count < maxPoolSize)
        {
            GameObject newObj = Instantiate(prefab);
            pool.Add(newObj);
            return newObj;
        }

        // All objects active and reached max, return null (or handle differently)
        return null;
    }

    /// Return object to pool
    public void ReturnObject(GameObject obj)
    {
        obj.SetActive(false); // just disable it
    }
}
#

something like this is a dynamic (create as u need) setup

lunar axle
#

Before digging in a rabbit hole, search up for github and use what they did first

rocky canyon
#

and usage:

if (Input.GetButtonDown("Fire1"))
        {
            GameObject bullet = bulletPool.GetObject();
            if (bullet != null)
            {
                // position bullet
                bullet.transform.position = firePoint.position;
                bullet.transform.rotation = firePoint.rotation;
            }
        }```
rocky canyon
#

jsut comes down to my organization skills and how fast i can find it 😄

#

thank God for indexing

scenic iris
lunar axle
rocky canyon
midnight plover
#

Addressables is also a good way to keep things running and reuse assetreferences

rocky canyon
#

no matter how trivial.. or if i even will re-use

#

its a burden

rocky canyon
#

like DLC

lunar axle
midnight plover
# lunar axle So liek prefabs?

If you use prefabs in a scene, they are loaded into memory, assetreferences can be used in inspector without adding the actual object to the scene. as the name states, its just a reference and will only load when you call it to, so no memory clutter because you packed everything into the inspector upfront

scenic iris
#

my biggest problem as game developer is although im solo development i try to make huge projects on my own and i have to do everything for code to 3D model or whatever.

rocky canyon
#

u get better work-flows as u learn

lunar axle
#

So meaning u can also save reference for scripts?

rocky canyon
lunar axle
#

And other stuff other than gameobjs

rocky canyon
#

if u guys were to make a script that moves a gameobject (x amount of units every x seconds but not smoothed )
like a step animator how would u do it? with coroutines or something else

midnight plover
midnight plover
rocky canyon
#

o thats neat

midnight plover
#

It basically stores all mono references that called it with the specific transform and check aginst null and what not. And in the end you just call it

this.Animate(yourTransform, Easing.AnimationType.LocalPosition, Easing.Ease.EaseInOutQuad, yourTransform.localPosition, nextPosition, duration);

for example

lunar axle
midnight plover
lunar axle
#

or u can create a new mono-behaviour script (call it Glide) that moves the object in Update()

coarse ibex
#

how do i destroy a gameobject through C#

slender nymph
#

what did google tell you?

coarse ibex
#

i did not ask google

night raptor
#

he might know

slender nymph
#

well there's your first problem. you're expected to make at least some attempt at researching your question before asking here because a 10 second google search can answer that easily

celest depot
#

And i did the pitch movement too

warm iron
#

Coding in project work is sooo easy, I can just write "I abandon it after several failed attempts" instead of writing codes

tired python
#

rezero!

rich adder
queen adder
#

Unity is trolling me
How is it possible that these two identical world transforms are in different places? They are not children of anything

silk night
queen adder
#

Ah

#

well now they look the same

silk night
#

they were always on the same spot

#

the handle just showed up on the center of each

#

instead of their origin point

queen adder
#

I know that the origin point at least for the 3d model is defined by blender. What's the center?

silk night
#

median center of all mesh vertices for 3d models i think

#

might also be bounds center, im not 100% sure

naive pawn
#

pretty sure it's bounds center, wouldn't average of vertices be biased to a dense part of the mesh

verbal dome
#

It uses the center of the total bounds of all colliders and renderers on the object

verbal dome
spare slate
#

Oh okay I see

#

My bad

lofty sequoia
#

If I have ClassB : ClassA and call StopAllCoroutines() in ClassA, will that stop coroutines running in ClassB?

naive pawn
#

these are instance methods, not static methods

slender nymph
#

are you calling it on the instance of ClassB? if not, then no. it only affects the instance that StopAllCoroutines is called on

polar acorn
#

Coroutines don't run on classes

lofty sequoia
#

I have an instance of ClassB and I'm calling a method in ClassA that calls StopAllCoroutines, basically wondering if for some reason it wouldn't affect ClassB coroutines

wintry quarry
lofty sequoia
#

Figured since B is an instance of A it should stop

wintry quarry
#

the inheritance is basically irrelevant, it's about the instance

naive pawn
wintry quarry
#

it's confusing

#

deactivating an object stops all coroutines on the object. but the docs are saying that stopcoroutine "Stops all coroutines running on this MonoBehaviour"

wintry quarry
naive pawn
#

the active state of a gameobject affects all its components updating as well, is it really that weird for that to also apply to coroutines

#

GameObjects also have no members related to coroutines

lofty sequoia
wintry quarry
#

the runtime doesn't really know if the StartCoroutine or StopAllCoroutines call came from B.cs or A.cs, it only knows which instance it was called on

scenic iris
#

i have found how to load values with Jason but for some reason the don't show my the string value.

this the 3 parts

JsonExample.json

{
  "playerName": "David",
  "isAlive": true,
  "score": 150
}

Data ```c
using System;

[Serializable]
public class SimpleData
{
public string playerName;
public bool isAlive;
public int score;
}

```c
using UnityEngine;
using System.IO;

public class LoadJsonExample : MonoBehaviour
{
    public string newPlayerName;

    void Start()
    {
        // Load JSON file from Resources folder
        TextAsset jsonFile = Resources.Load<TextAsset>("JsonExample");

        // Convert JSON text to class
        SimpleData data = JsonUtility.FromJson<SimpleData>(jsonFile.text);

        data.playerName = newPlayerName;

        // Now you can use the values
        Debug.Log("Name: " + data.playerName);// The don't show my the String value hear the other 2 below show correctly 
        Debug.Log("Is Alive: " + data.isAlive);
        Debug.Log("Score: " + data.score);

        // Example usage
        if (data.isAlive)
        {
            Debug.Log(data.playerName + " is alive with score " + data.score);
        }
    }
}
keen dew
#

data.playerName = newPlayerName; overwrites the value. Did you mean to have this the other way around?

wintry quarry
#

yep you're overwriting it with whatever is in the inspector

#

Also I love that you got Jason to work for you, he's a good fellow

scenic iris
#

yap now it's working thank you save my for a lot of trable

potent portal
#

which way is the correct way of doing the curly brackets 🙏

midnight tree
potent portal
#

i honestly prefer the bottom one

rich adder
#

But there is no right or wrong

midnight tree
potent portal
#

okay why the hell is "?" automodded

rich adder
#

Why do you need to send less than a few chars message when you can edit it or react to post

potent portal
#

ah

#

makes sense

midnight tree
twin pivot
potent portal
#

im so confused, it has the same name how would it not be used?

midnight tree
potent portal
#

nevermind i figured it out

#

it was some weird syntax error

grand snow
#

you have done something weird here the function ReloadLevel is either outside the class or the above ones are all local functions

glad shore
#

how do i get my license back?

polar acorn
# glad shore

Try signing out of the hub and signing back in again

rich adder
potent portal
#

Reflection?

#

I’m sorry I’m like really new to C# 😭

rich adder
#

At very least you can do nameOf keyword
Invoke(nameof(ReloadLevel)) to avoid spelling errors but still. Learn coroutine if you want delay

potent portal
#

Okay.. got it

grand snow
#

invoke is fine as a beginner but better ways exist as said above

rich adder
#

Oh didn't see Norman sent the nameof thing. Mobile network slow as hell 😆

grand snow
#

nameof() is such a good language feature

midnight tree
grand snow
#

Invoke asks the engine to invoke some function with a name at some point in the future

#

(thats how many unity messages work anyway, the engine directly invoking functions in the CLR)

#

Fun fact, unity recommend doing your own "update" calling in c# (for lots of objects) as that can be a lot faster than relying on unity to call it on many monobehaviours

#

there is greater cost to native-managed crossover and unity even doing the managed call native side

vestal cosmos
#

i need some help i cant open or create a project and i dont know what the problem is(forget this message it somehow fixed itself thanky you unity god)

cosmic dagger
grand snow
sour fulcrum
#

Maybe I'm tripping but I feel like that ends up kinda happens naturally once you get more comfortable with c# since you end up doing a lot more stuff outside of the update loop and more via callbacks or coroutine/async type shit

#

maybe im not dipping my toes in the right genres tho idk

#

i just seem to slowly start not having much in update

grand snow
#

If you know programming, OO and good design its more natural to not over use unity messages

#

I much prefer to init and control things myself because otherwise you have to do stupid shit trying to get by only with Awake/Start

cosmic dagger
sour fulcrum
#

blessed genre

#

the td i made for a like 4 day gamejam has more sauce than some of my month long projects

grand snow
#

It was a hybrid but had things moving along a path and towers to shoot the enemies.

cosmic dagger
#

Once I started pooling objects, Init became a necessity. I think I started using a custom update when I created an object and separated each of its behaviors into its own script, and called OnUpdate from the main controller (or brain) . . .

sour fulcrum
#

It would be so nice if we could have proper constructors directly

glad shore
#

how do i get visual studio code to work with unity
ive already installed it but i cant create scripts

frosty hound
#

!ide has the guide for configuring it.

radiant voidBOT
grand snow
sour fulcrum
#

forsure

#

i still gotta keep tinkering with my prefered setup for ideal init with so's and prefabs

#

it's almost there but then trying to handle netcode for gameobjects with it just blows it all up 😄

timber tide
#

I think rider has some features to warn you to use an Init method when instantiating

#

there's some useful utility like forcing to use a return value

clever path
#

Is anyone able to help me with getting my crouch height/ceiling detection work? I created a forum post in code-general, been stuck on this for a couple days and I've looked at a ton of videos, forums, unity documentation. my current setup "works" but its super janky and has all kinds of issues

rich adder
clever path
ivory bobcat
#

You may want to link to any information that you had previously provided.

sour fulcrum
finite flower
#

Okay, idk what to search to get what I want, but I know of it.
Is there a function or something (i don't remember what it's called) that pauses a script for a set amount of time/frames?
Like, I want to have a script that runs, then holds for one second, then runs.

#

(There might actually be a much better way to do what I'm trying to do tbh...)

wintry quarry
finite flower
# wintry quarry You're looking for coroutines

Okay, after looking into it, I'm seeing a lot of stuff saying only to use coroutines if I need to repeat things, which is not what I'm doing. I just need to make the script hesitate before checking something.

wintry quarry
#

Use a coroutine for any code in which you wish to insert inline delays

#

Not sure what you're reading

#

Repeating things is done with loops, another subject entirely

#

You can certainly put a loop inside a coroutine but there's no requirement to do so

finite flower
#

just several forums talking about where and when to utilize coroutines because I was trying to find documentation for IEnumerators

wintry quarry
#

You will confuse yourself with that. Just look up Unity coroutines

#

It uses that type, and there's a technical reason why but it's not necessary to understand it to use them

sour fulcrum
finite flower
#

it's using IEnumerator in the coroutines, and I'm getting an error saying that IEnumerator doesn't exist 😅

sour fulcrum
#

might be missing a using, does it have a suggested fix?

wintry quarry
#

No it's saying "are you missing a using directive"

finite flower
#

which is why I was trying to find documentation for IEnumerator

sour fulcrum
# finite flower Okay, after looking into it, I'm seeing a lot of stuff saying only to use corout...

The issue with wanting to make a "script hesitate" is that code runs in order, if you have this logic

wait until (x happens)
thing that makes x happen

x can never happen because the code will be stuck on the wait.

Coroutines work in a way where are kinda "submitted" to Unity and every frame Unity will check up to see how it's going without interrupting the code because now it's

Start Coroutine();
Unity collects Coroutine
Unity checks Coroutine
Unity looks for condition in active coroutine (the condition being wait until x happens)
The condition replies with false
Unity carries on with it's day

wintry quarry
finite flower
#

Okay, I've got it working, now another probably simple question...
Is there a simple way to check if a boolean changes state?

wintry quarry
#

But if you're just looking for the namespace your IDE should be telling you automatically

finite flower
radiant voidBOT
finite flower
#

I mean, it autocompletes, but it doesn't like.. suggest code stuff?

#

anyways, that's not really an issue

slender nymph
#

get your IDE configured using the guide linked and it will work

finite flower
#

It's already configured

slender nymph
#

do errors get underlined in red?

finite flower
#

Is there a simple way to check if a boolean changes state?

finite flower
#

my VSC was in restricted mode, that's why it was being screwy 🤦

hardy wing
#

there's no automatic notification system unless you set it up that way (with for example C# events)

finite flower
#

I'm having such a hard time with making my character go between walking and climbing, I feel like I need a more robust detection method or like... knowing whether the player is on the ground or trying to climb but idk

gaunt cipher
#

you ever just sit there being like why won't my event fire why won't my eve- oh.. I didn't invoke it.. I'm that dumb

finite flower
#

how do I make a coroutine just like stop? It keeps asking for a return, and if I try to make it return nothing, then it gives and error, and if I do anything else, the coroutine never even runs 😭

sour fulcrum
#

post your code

#

coroutines are a little weird looking when you first use em don't worry

finite flower
finite flower
#
private IEnumerator ClimbCheck()
    {

        if(!isClimbing && wallFront)
        {
            if(!climbHold)
            {
                Debug.Log("started climbing");
                climbHold = true;
                StartClimbing();
                StopCoroutine(climbCheck);
            }
            
        }

        if (!wallFront)
        {
            Debug.Log("stopped climbing, no wall");
            climbHold = false;
            StopClimbing();
            StopCoroutine(climbCheck);
        }

        if(isClimbing)
        {
            if(isGrounded)
            {
                Debug.Log("stopped climbing, hit floor");
                climbHold = true;
                StopClimbing();
                StopCoroutine(climbCheck);
            }
        }

        yield return new WaitForSeconds(1.0f);
    }
sour fulcrum
#

thats fine for small snips, you can add cs after the three thingos for better formatting

#

same line

finite flower
#

no clue 😅

sour fulcrum
#

its fine lol

finite flower
#

it just isn't lmao 😭

sour fulcrum
#

oh you want the start of your code to be on the next line

naive pawn
#

(and the last ``` to be on a separate line as well)

sour fulcrum
#

there we go

finite flower
#

🙏 ty

polar acorn
naive pawn
#

that last yield return doesn't have anything after it, you're waiting to do.. nothing?

#

also you don't need StopCoroutine to stop the current coroutine, you can use yield break; instead

sour fulcrum
#

so yeah yield break can work
this is because what you return in a coroutine is basically you telling Unity what's the status of the coroutine,
so when you return new WaitForSeconds() your telling Unity "hey do this before checking up on me again" or break is telling Unity they can finish up with it

finite flower
#

yeah, this is what happens when I'm just told "use a coroutine" and nothing else 😮‍💨

sour fulcrum
#

learning is incremental 😄

naive pawn
#

hey, no errors, this is learning progress lol

sour fulcrum
#

You didn't ask for it but would you be interested in a little advice on a slightly "better" way to approch what that code is doing?

polar acorn
finite flower
#

I was thinking that if I can pause the check for if the player is trying to climb, the code that's doing the transition between climbing and not climbing would actually work smoothly and not jitter around

polar acorn
#

So, you could run a line, wait 1 second, then run another line.

Or, you can do a yield return null which waits one frame and resumes next frame

naive pawn
#

the coroutine is in its own realm, any yields you do inside won't affect the timing of stuff outside

finite flower
#

I'm probably using the right thing, I'm just not seeing how I need to put it all together for it to work

#

I have all the right pieces, but no instruction manual 😅

#

The issue I'm having is that when the player is trying to climb, it calls for StartClimbing() and StopClimbing() at the same time until one wins out because I don't have a clean way to detect when the player is trying to climb, I can only detect when they are standing at a wall and trying to move and if they are touching the ground.

naive pawn
#

i feel like ive commented on this before

finite flower
#

SO my thought was to slow down that actual process and not call one until the other has tried to run through, and maybe that would make the transition smooth

finite flower
naive pawn
#

startclimbing when you actively move up, stopclimbing when you actively move down
opposite checks, so it shouldn't jitter

finite flower
#

moving up and moving down are not things that I am or idk if I even can read for

naive pawn
#

well you don't seem to be using player input in the checks in that coroutine

sour fulcrum
naive pawn
#

those checks are the basis of my idea lol

finite flower
naive pawn
#

well, how is it set up?

finite flower
#

lots of spaghetti

naive pawn
#

that doesn't really affect what you can and can't do, just difficulty

sour fulcrum
#

straightening spaghetti is a war that can be won in many small battles

#

we're probably gonna have to pick a fight or two here to get what you want

naive pawn
#

-# well that sounds cursed out of context

finite flower
#

I go back on myself a lot, and I'm scared to try touching it cause it'll break what I have and will add a week of fixing just to get back where I am 😅

sour fulcrum
naive pawn
#

well we can't really give much guidance here without seeing your code

#

perhaps share the full script

#

!code

radiant voidBOT
finite flower
#

With Paste of Code, I just paste it in and send the link here?

naive pawn
#

yes

#

well you gotta hit save too

#

otherwise you just link the homepage

finite flower
clever path
#

Spent 2-3 days trying to fix the crouch height collision scripts, watched a ton of videos, looked at a ton of forums, and the issue was in one of the tutorials I saw they told me to scale player 2,2,2. So all my ceilingcheck scripts were failing and I thought it was some issue with centering/changing the origin of the object... changed it to 1,1,1 and reverted some changes and it works perfectly now...

finite flower
#

mentally preparing myself to be destroyed

naive pawn
#

well you have those InputActions

#

tbh im not sure you even need a coroutine for this

finite flower
#

I will say that I don't really use // for notes, mostly just saving code I've replaced in case I want to go back or need to see it

finite flower
naive pawn
#

basically just this, continuously

finite flower
#

hol up

#

no no, I'm doing that

#

I think

#

Yeah, I'm trying to do that with the IsClimbing and IsGrounded variables

#

I just don't check specifically moving up or down, just moving because I'm translating forward and backwards into up and down

naive pawn
#

but you aren't checking input

naive pawn
#
if (moveLike != Vector3.zero)
{
  isMoving = true;

  WallCheck();

  if (wallFront && !isClimbing)
  {
    //Debug.Log("Start Climbing");
    StartClimbing();
  }

like consider this snippet, if you walk up to the wall and then walk away, you start climbing. the direction is important here.

finite flower
#

otherwise the player moves strictly on X or Z coordinates

naive pawn
#

oh, going off the directions of the camera, i see

#

gotta see if you're walking into the wall then

finite flower
#

The camera if not climbing, the physical direction the character is facing if they are climbing

finite flower
#

tbh, idk what I'm actually using wallLookAngle here for

#

I can prolly get rid of it

naive pawn
#

this does not check if you're walking into the wall

#

this checks if you're looking at the wall

#

the player input is important here

finite flower
#

idk how to check that

#

with the way my movement is set up

#

cause all I know to check the movement would lock it to the worldspace X and Z, not the players forward vector

naive pawn
#

could probably split it into 2 steps

  • figure out the direction from the player to the wall (or the wall's.. anti normal, i guess)
  • see if you're walking approximately in that direction
#

the latter part could be done by getting the Angle between 2 vectors and see if it's within a range

finite flower
#

so wallLookAngle is my savior in the end lmao

naive pawn
#

oh, yeah, raycasts have normals
then yeah that seems like it'd help

finite flower
#

How do I check if the player is moving in the direction of the wall?

naive pawn
#

check if you're going in roughly the direction of the antinormal

#

(probably projected onto the XZ plane)

finite flower
#

I'm going to say a lot of choice words

#

I didn't even have to do allat

#

I literally just had to remove this

#

And add this

#

now it works exactly how I wanted and fixed literally every problem I was struggling with and was planning on fixing

naive pawn
#

ok now what if you walk up to a wall from the side

finite flower
#

doesn't start climbing until you're basically facing the wall

#

I can make it a little tighter, but otherwise it's kind of annoying to get that kind of angle anyways

naive pawn
#

you can face the wall with no Z movement

finite flower
#

this is the forward/backwards variable for movement

#

like, the direct input

#

basically W key or S key (not literally tho)

naive pawn
#

and you can walk up to a wall without going forwards/backwards

finite flower
#

you can even jump off walls now, I thought I was gonna have to code that in

#

although I want to make the player launch backwards, but I'll have to figure that out

midnight plover
finite flower
midnight plover
finite flower
#

No, when you're climbing a wall, you press jump and you jump backwards off of the wall.

midnight plover
wintry quarry
#

Using a joint

#

And a line renderer

#

And the layer collision matrix

lost briar
hexed terrace
#

this is a code channel, so.. not the right place. If you can't find a channel specific to your question, don't use a random one.. use #💻┃unity-talk

#

delete from here and ask in there

craggy marsh
#

Sure, thanks

opal zodiac
#

what helped yall figure out state machines? right now its been kicking my ass for a few days and i cant figure out how to properly set it up

wintry quarry
#

(which I learned in school)

slender rapids
#

does anyone know how I would put a texture as a floor on my 2d top down game, Im not sure about a good way to go about it. I want to have different biomes with different floors

solar hill
#

sounds to me like you should probably use a tileset for that rather than a singular texture?

sterile drum
#

Hi, I'm new to Unity and I want to learn the basics of programming for a shooter game I want to make.

frail hawk
#

check the pinned messages of this channel

crude dock
#
using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    PlayerInput playerInput;

    InputAction moveAction;
    InputAction lookAction;

    private Transform cameraTransform;

    public float movementSpeed = 50.0f;
    public float mouseSensitivity = 1.0f;

    private float cameraPitch = 0f;

    void Start()
    {
        playerInput = GetComponent<PlayerInput>();

        moveAction = playerInput.actions.FindAction("Move");
        lookAction = playerInput.actions.FindAction("Look");

        cameraTransform = GetComponentInChildren<Camera>().transform;

        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        Move();
        Look();
    }

    void Move()
    {
        Vector2 input = moveAction.ReadValue<Vector2>();

        Vector3 camForward = cameraTransform.forward;

        camForward.y = 0f;
        camForward.Normalize();

        Vector3 camRight = cameraTransform.right;

        camRight.y = 0f;
        camRight.Normalize();

        Vector3 movement = camRight * input.x + camForward * input.y;

        transform.position += movement * movementSpeed * Time.deltaTime;
    }

    void Look()
    {
        Vector2 look = lookAction.ReadValue<Vector2>();

        float mouseX = look.x * mouseSensitivity * Time.deltaTime;
        float mouseY = look.y * mouseSensitivity * Time.deltaTime;

        transform.Rotate(Vector3.up * mouseX);

        cameraPitch -= mouseY;
        cameraPitch = Mathf.Clamp(cameraPitch, -80f, 80f);

        cameraTransform.localRotation = Quaternion.Euler(cameraPitch, 0f, 0f);
    }
}

can anybody explain to me why no matter what value i set sensitivity and move speed, they dont change in game?

solar hill
naive pawn
#

it's already per-frame

solar hill
#

also yeah

#

keep it for movement

#

for mouse you can just do

float mouseX = look.x * mouseSensitivity;

solar hill
#

thats your problem

#

you have public values

naive pawn
#

the values in the script are just the default

solar hill
#

the inspector is overriding them

naive pawn
#

when they're serialized, in an actual component, the serialized values take priority

solar hill
#

whatever you had in the inspector initially will always remain until you change it there

naive pawn
#

change your values in the inspector instead.

solar hill
#

you should still remove the deltaTime from the mouse look

crude dock
#

oh okay, didn't expect that, thought that they are synced

#

thank you!

naive pawn
#

nah that would make tweaking specific instances impossible and completely negate the point of having serialized variables

crude dock
#

ill just change them to private id rather have the code control the thingy

wintry quarry
naive pawn
#

you should not

naive pawn
#

(it also means you can reserve the value in code for specifying the default when you create a component, making the distinction actually useful)

crude dock
#

aight, the movement speed works now, but after removing the time delta from mouse, it turns at the speed of light

polar acorn
#

You will need to adjust the numbers

#

But now it is not negatively affected by frame rate

crude dock
#

wait yeah nevermind sorry i forgot to change it

#

hehe

#

yeah everything works

#

thank you so much

coarse harness
#

Hi, I'm just starting to learn Unity and I wanted to know the most optimized way to load maps in first-person 3D games, and if possible, could you give me the names of those methods so I can do a more focused search?

rough granite
timber tide
#

Most optimized way is usually addressables/assetbundles if we're talking about mem management

#

just a quick way to load/deload all the dependencies of a level

coarse harness
wintry quarry
#

Beginners worry way too much about "optimization". Get your game working first

timber tide
#

Yeah, I wouldn't worry about mem and just cache all the prefabs

#

and init what you need

solar hill
#

even the project you described seems awfully ambitious for a newcomer

wintry quarry
#

For now all you need to know is you can load scenes with the methods in SceneManager

#

and you can instantiate prefabs with Instantiate

finite flower
#

What is used to make a list of objects? Like... I know what it is, but I cannot remember the name for the life of me.

coarse harness
#

Well, it's not that this is my first game (just my first 3D one), but I wanted to know at least the name of this method so I can research it (also because I can't afford not to worry about this since my PC isn't one of the most powerful, so it would be good to avoid things like this).

finite flower
#

It was something with an 'A' I thought?

#

It might just be a list I'm thinking of, idk

slender nymph
#

do you mean an array? because that's like a list but not resizable

solar hill
#

youre thinking of arrays

finite flower
#

yes

wintry quarry
#

They might be thinking of ArrayLists even

finite flower
#

thank you, I was blanking so hard 😭

wintry quarry
#

Arrays and lists are related and similar. Lists use arrays inside. You should learn both

finite flower
#

I know, I just know for this specific application, I was needing an Array, I just couldn't remember the name

slender nymph
#

so just to confirm, you need a collection that you cannot add to at runtime? because that's why you would choose an array over a list. a list can be added to or remove items, an array is fixed size

finite flower
#

Yes, I'm using it to hold the different pages of the player's "Inventory"

#

and then change through them as the press "Next Page" or whatever

#

I am now thinking there would be an easier way to set the page than what I was initially thinking after setting up the array 🤔

#

Is there a good way to set the active item to the current array value? And have the others inactive?

naive pawn
#

what do you mean by "current array value"

finite flower
#

Cause my first thought is to just compare it to an integer that's changed by pressing "Next" and "Previous"

finite flower
naive pawn
#

well then you would set the current page to be active and the other pages to be inactive
if you remember what page you were previously on, you can set just that page to be inactive (assuming all other pages are already inactive)

#

if you don't want to make that assumption or if you don't want to have to remember that, you can just loop and set them all to the proper active state

#

it's a noop to deactivate an inactive object anyways

finite flower
#

Yes, I'm just thinking there might be an easier way than a long if statement 😅

naive pawn
#

you would not have a long if statement

finite flower
#

then idk what you're saying I can do

naive pawn
#

you can just loop and set them all to the proper active state

finite flower
#

that means nothing to me

slender nymph
#

just keep an int that corresponds to the index of the active page. then when you switch pages, you just change that int then loop through the array of pages, if index == that int, set page active, otherwise set inactive. you literally just do pages[i].gameObject.SetActive(i == activeIndex); (changing relevant variable names as necessary) assuming you are just enabling/disabling them

finite flower
wintry quarry
#

the more efficient way is to just track the currently active page. When you switch pages you deactivate the current one and activate the new one.

slender nymph
#

yeah but that's only really marginally more efficient and really a microoptimization if they only have a few pages anyway

solar hill
#

A bit of a structural question i guess,
Im refactoring my status effect system in my game, and the way im currently doing it is like this:

When an effect like "Burn" for example is applied, a singleton effectsmanager looks up its data in a dictionary, gets the pre cached script type for that effect and it applies it. Because the effect types are resolved and cached at startup, theres no reflection during gameplay just quick lookups and method calls.

Do you guys think this would be efficient? Or should i not use a dictionary lookup for this. It allows me to keep all effects as individual IDs hardcode in a static class.

wintry quarry
#

sounds fine

grand snow
#

does it need to be a monobehaviour?

#

basically you dont always have to make things a mono singleton

solar hill
#

The Singleton that maps the IDs to their respective Assets is an MB

grand snow
#

does it require mono messages or serialized variables?

#

Sometimes its easier or better to have a static manager or one you init and use

solar hill
#

Youre right

#

it runs once on start up anyways

solar hill
#

thanks