#💻┃code-beginner

1 messages · Page 334 of 1

finite dew
#

just type in unity tutorial, mark brown from GMTK has a good one
https://youtu.be/XtQMytORBmM

🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴

Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...

▶ Play video
shell gorge
#

Ty!

summer stump
#

I also just linked you to the official one right there
The GameMaker one is the only one I like on youtube though, so if you go with that, it's a good choice

limber anchor
#

!code

eternal falconBOT
limber anchor
#

Hello I am making a fps Movement controller and for a groundcheck I am using the CheckSpyhere method but its returing true even if its not colliding with a Object in the Ground layer
code: https://paste.ofcode.org/xV9E98bKEi9SHP2nxavBVc

wraith grotto
#

Hi hi, good people!

I have an issue loading gameObjects that render my sprites depending on the weapontype picked up. The gameObjects are children of the main playerObject which the following code is linked to.

the code: https://hastebin.com/share/siramugafo.csharp
the error: https://hastebin.com/share/enixadekop.vbnet

I have set the gameObjects in the serialized fields in the unity editor

finite dew
#

I'll try to find it

limber anchor
willow scroll
willow scroll
finite dew
# limber anchor alr ty

the way I do it in my project rn, is just selecting it in the inspector instead of through LayerMask.GetMask

[SerializeField]
private LayerMask _layerMask;
#

because LayerMask.GetMask returns the mask in a different way than physics cast expects it

#

beyond me, why

#

but this method works

limber anchor
finite dew
#

the way you do it right now makes it collide with everything

finite dew
#

it's beyond me why it's this way but yea do check it out

limber anchor
finite dew
#

it can't be debugged in debugger but Debug.Log is always there :D

limber anchor
finite dew
#

that's a funny way to find this out

limber anchor
finite dew
# limber anchor XD

ok, unity says to get the index of the layer you want
and do
int layerMask = 1 << indexOfLayerYouWantToCollideWith;
I'll check too, if this works

limber anchor
#

I have setup this loop ``` Collider[] colliders = Physics.OverlapSphere(GroundCheckTransform.position, GroundDistance, layerMask);

    Debug.Log("Number of colliders detected: " + colliders.Length);

    foreach (Collider col in colliders)
    {
        Debug.Log("Collider name: " + col.name);
        Debug.Log("Collider position: " + col.transform.position);
        Debug.Log("Collider tag: " + col.tag);
        
    } ``` but it always returns 0 even if I am standing on the floor and when I am in the air
finite dew
# limber anchor XD

ok, so my layer that I'm targeting is layer 6 in the editor, so doing 1 << 6 for the layer works
but doing 1 << LayerMask.GetMask("Floor") does not work
Also idk, now I tested it again and my first method with just selecting in the inspector worked, that's weird

finite dew
shell gorge
#

I’m not sure what I’m doing 😅

finite dew
radiant imp
#

hello guys

limber anchor
summer stump
#

Just get LayerMask.GetMask and use that directly

radiant imp
finite dew
summer stump
radiant imp
summer stump
radiant imp
#

like TABS

summer stump
radiant imp
#

but if you know please tell me

radiant imp
shell gorge
summer stump
#

On my phone. But literally "unity active ragdoll" will get it

limber anchor
radiant imp
#

fr?

finite dew
# summer stump Which part?

fine, I give up, I checked the actual values, and it seems to all return the same stuff
I have no idea why it just didn't work for me before

#

¯_(ツ)_/¯

finite dew
limber anchor
#

but now it detects nothing again

summer stump
finite dew
summer stump
#

And is this for a raycast or something? Have you done a Debug.DrawRay?

finite dew
#

and use the inspector for it

limber anchor
summer stump
finite dew
#

raycast and spherecast is pretty similar

finite dew
summer stump
#

Ah, spherecast? Same difference then

#

Still do a drawray just to check distance, start position, and direction

finite dew
summer stump
#

Ah ok

finite dew
#

I feel like there's some catch somewhere
a silly small mistake that's tough to find that's causing all this
I think we eliminated most possibilities of error here

#

like is the floor layer set properly, for example

shell gorge
radiant imp
#

Hmmm all the stuff is self balanced ragdolls instead of ragdoll movement 🤔

limber anchor
# finite dew with spherecast

its somehow colliding with its parent object in mid air which I think sets the Grounded to true because ofc its colliding

finite dew
#

go through the tutorial from scratch

shell gorge
#

Okay.

radiant imp
finite dew
shell gorge
#

Does the video have something to do with a point light?

#

I just need this point light over with

finite dew
limber anchor
shell gorge
#

Ah ok.

limber anchor
#

I made the Collider of the Character controller On the parent smaller

#

and then made the groundcheck distance lower

#

with resulted in them not colliding anymore

stoic glen
#

Why can't I add a child of a prefab as an Game Object

finite dew
limber anchor
#

XD

#

not for me right now

finite dew
limber anchor
#

as its almost 11 pm XD

vestal stump
#

Random.Range keeps generating numbers when on the update function and if i put it in a void it still generates multiple numbers is there somewhere i can put it to where itl generate just one number when called

radiant imp
#

Is there a place to hire ppl?

stoic glen
vestal stump
#

kk ill try that

stoic glen
shell gorge
#

I’m working on something 3D

stoic glen
frosty hound
eternal falconBOT
shell gorge
#

Just having a hard time trying to do this, I need a clear Tutorial on how to put a point light on a Player

#

Gonna take a break from it.

rich adder
shell gorge
#

Yeah and I’m having the hardest time over it lmao

#

I have a hard time learning alot, but I try my best to understand.

summer stump
#

Do the !learn guide. You need to know these extreme basic things

eternal falconBOT
#

:teacher: Unity Learn ↗

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

shell gorge
#

I am going to try that when I’m back on, I’m taking a break, Tysm.

summer stump
#

Seriously, at LEAST after fixing the light (preferably even before), do the guide above

lost anvil
#

is it possible to access a materials emission intensity through code?

final trellis
#

not sure how to describe what i need help with, but basically, i want the m_mustaches part to be from a string input, but idk how to parse that string into something usable

#

also dw yes ik i should have -1 at the end of m_mustaches.Count, but im using 1 above the list count to kinda represent null

deft grail
#

you want to turn that into a number?

final trellis
#

nah i want to turn the string into the whatever you call it to the list

shell gorge
final trellis
#

idk the correct terminology for what im looking for

deft grail
final trellis
#

the variable name of the list

#

so a string input of "m_mustaches" will get the list size of the m_mustaches list

deft grail
final trellis
#

kind of like how you specify what variable to change in an animator through code by using a string

deft grail
#

not sure if theres a method for that

#

for now the best would be create your own which just returns the count based of the string by using if statement

#

not sure if there is a better way

final trellis
#

unity seems to be able to do it so i should be able to too

#

i think?? idk

deft grail
#

you are basing of C#

verbal dome
#

If you really really want to do that

#

Or if it's for editor only, you can use SerializedProperty etc.

#

But if you only have a few different names then you could just do it manually with an if- or switch-statement, like gr4ss said

eternal needle
final trellis
#

the use case is that i can call this function from a UI element, theres left and right incriment buttons and it saves the mustache ID to a playerpref, but im realizing now that buttons and sliders dont really like to call functions with multiple input fields 💀

#

the point of making it that way was so i diddnt have to make 43087524078 functions with 99% the exact same code but with just a tiny little change of what list it was looking for

eternal needle
#

i dont see how the "m_mustaches" part is relevant to button calling a function, these buttons can directly call your function for going to the next or previous option

final trellis
snow girder
#

hey guys so I'm trying my hand at the new and improved unity input system, but for some reason my script can't find my input actions asset

#

can anyone tell me why

eternal needle
# final trellis its so i can specify which button affects which list ( bc i also have ``m_beards...

it really is simplest to just have a function for everything thats needed, like a function for CycleNextMustache and CyclePrevMustache and then both functions can call some ChangeMustache(int index).
Having this try to work for everything like beards and whatever else exists is gonna be way more of a pain. Like if in the future you suddenly want to handle beards differently, then you're gonna either going back to making specific functions for beards or trying to adapt this "all in one" system.

final trellis
#

fair enough, was just looking for a way to make it more simpler to use

eternal needle
snow girder
#

its telling me it doesn't have the inputactions at cs 22

eternal needle
#

and then you can see why its not set to an instance

snow girder
#

oh wait

#

i see

#

you could've just said start happens after onEnable but whatever

#

thanks for your help

eternal needle
eternal falconBOT
acoustic arch
#

my first looks at my enemies ai

#

it looks extremely messy and its my first time attempting something like this, its meant to find each ability/card and weight them whether they should be used as the action

#

does anyone notice a big things that i should change?

rare basin
#

that code is totally not correct

#

imagine if you have 100 abilities

#

would you do public Weight cardAb1Weight;

#

100 times?

#

then 100 ifs?

#

do you know what's a Dictionary and how to use it? or Lists/arrays?

#

you then can have Dictionary<Card, int> cardWeights for example, and the value of the dictionary is each card's weight

#

then make a function that picks one of the card based on a weight picking system

#

also the functions ab1W, ab2W - again think in a bigger perspective

#

if you want to add more cards and abilities this is just pain in the ass to work it

#

with 10 abilities you need 20 functions for it

#

and 20 additional variables

#

@acoustic arch

acoustic arch
#

i alotted a lot of time to work on the enemy ai so i expected some work

acoustic arch
#

itll make it much cleaner

acoustic arch
rare basin
acoustic arch
#

it lowk making me wanna kms

rare basin
#

and noone will understand whats going on in this code

acoustic arch
#

the abilities are their own SO's so for the most part making them is irrelevant but i would agree its extremely messy

rare basin
#

i get it, but you dont get what im saying

#

if at any point in the development, you or your team or your boss or whpever

#

decide that now enemies have 5 abilities instead of 3

#

you need to add like 6 variables and 6 functions and 12 ifs

#

instead of adding 2 abilities into a list/dictionary

#

you should learn about SOLID principles, especially the open/closed principle

#

this means that a class should be extendable without modifying the class itself

acoustic arch
#

alright i think i know how to fix it (mostly involves deleting a lot)

#

i need to look into disctionaries first tho

#

thanks

acoustic arch
#

Action contains the details of what happens if that ability or etc gets called

#

i deleted the whole thing, too messy couldn't read

rare basin
#

starting from scratch is often a very good idea

ivory bobcat
acoustic arch
#

i wiped the slate

acoustic arch
#

before getting into it

ivory bobcat
acoustic arch
#

and i didn't like reading it

devout spire
#

how do i stop a foreach function without stopping the function it's contained in? in my code the return is ending the entire runcommand function but all i want it to do is stop the first foreach and move on to the one after it.

    {
        command = "";

        foreach(char ch in fullcommand)
        {
            if(ch.ToString() != " ")
            {
                command = command + ch.ToString();
            }
            else
            {
                return;
            }
        }

        foreach(string s in commands)
        {
            if(s == command)
            {
                log.text = log.text + System.Environment.NewLine + "User>" + command;
                return;
            }
            else if(s == commands[commands.Length - 1])
            {
                log.text = log.text + System.Environment.NewLine + "User>" + command;
                log.text = log.text + System.Environment.NewLine + "No such command '" + command + "' found!";
            }
        } 
    }```
devout spire
rare basin
real falcon
#

what value do I use in a heightmap for an area which should not be modified

rare basin
#

huh

real falcon
#

if I dont want that pixel to be raised or lowered visually

wintry quarry
#

In what context

#

Why are pixels being raised and lowered in the first place

opaque hinge
#

I am currently working on a code that generates a hexagon grid of gameobjects and add them to an array. Each gamobject has a node script associated with it. I then randomly shuffle the array and delete the first 14 items from the array, to randomly destroy 14 tiles from my grid. I then call a function called getneighbors for every tile in the array that essentially creates an array of all neighbor tiles. However, for some reason, despite the get neighbor function being called after tiles are already destroyed from the tile array, the neighbor array for each tile will contain blank array members, instead of just a smaller array. I dont know if Im explaining myself well, and I can share any code if tha would help

teal viper
real falcon
#

like a heightmap is a grayscale image where black is lowered and white is raised

#

what if I dont want that pixel to be either

verbal dome
#

Consider using a List instead of array, and also removing the items (gameobjects) from that list when you destroy them

teal viper
real falcon
#

I dont im just using the default unity heightmap on the URP/Lit shader

teal viper
verbal dome
teal viper
#

I see

real falcon
verbal dome
real falcon
#

I mean I could just brute force to find one but id rahter be precise

opaque hinge
verbal dome
real falcon
#

just a png in gimp, idk what export settings im using

#

ill try the linear color space thro

verbal dome
#

Could try to use a coroutine and WaitForEndOfFrame to get around that. But I'm just speculating here

#

Sharing your code would help

real falcon
#

I think that was it, yeah, the import color space

verbal dome
#

That should make it linear

real falcon
#

yeah it worked

verbal dome
#

Nice

#

Btw you should do that to anything that isn't an Albedo/Base color texture as far as I know

#

My MaskMaps were really weird until I realized they were imported as sRGB

real falcon
#

im not sure what that means

#

as in just the base texture?

verbal dome
opaque hinge
#

for example I go, for each tile in the list, add tile to public list, and then I get neighbors for tile. And the public list doesnt show any null values, but the neighbors list does

eternal falconBOT
verbal dome
#

I'll probably sleep soon but me or someone else can probably take a look

opaque hinge
#

okay thanks

verbal dome
#

You should show that too

opaque hinge
#

yes thats it,

teal viper
opaque hinge
#

I dont have unity open right now but there wasnt last time I checked

verbal dome
#

I don't see you removing anything from nodes though

#

You are destroying some of the nodes in SetBoard, so you end up with null nodes in the nodes array, right?

#

Then you pass a list of those nodes into FindNeighbor

#

They become null at the end of the frame, that's how Destroy works

#

So FindNeighbor is checking neighbors that are about to become null/get destroyed

#

As far as I can tell

opaque hinge
#

Yeah I did think that, which is why I had this //nodes[i] = null; , but when I added that, tilelist was completely empty all of a sudden

verbal dome
#

This is why I originally suggested using lists, not arrays. Instead of setting it to null in the array, you could just remove the node from the list at that index

opaque hinge
#

yes I am, okay.

verbal dome
#

I hope my explanations aren't too confusing 😄

opaque hinge
#

Im honeslty not even sure what the point of that nodes array is though. Since every tile has a node attached to it, can't I just find neighbor for the node of every tile in the tile list

verbal dome
opaque hinge
#

Okay, I will probably try that because Im not sure why I added it in the first place, I think chatGTP recommended it

verbal dome
#

:/

regal bear
#

Hi, i have some stats working fine, hunger, thirst, fatigue, needs, but i guess my code is a mess. Can i somehow unify the stats? Every stats work the same, can i somehow chain the stats to a for each? or something like create a container for my stats and go through every stat and do the same thing? Im not familiar with C# yet, and still a beginner coder

opaque hinge
#

thanks Osmal

grave sage
grave sage
regal bear
regal bear
#

maybe player stats the thing, where i just write the code once, and doesnt care after that

grave sage
grave sage
regal bear
grave sage
#

example

 if (currentHunger < 1 ) { KillPlayer(); }
 else if ( currentHunger < 30) { ReducePlayerSpeed(); }
#

then u have to actually create those two functions KillPlayer() and ReducePlayerSpeed()

regal bear
#

yea i know that, my problem is to like shorten the code. i want something like i have currentHunger, hungerRegen, currentThirst, thirstRegen (Start Regen when i do something) and then a function which works independently so a function, takes current hunger, and hunger regen, and do the regen code, but i need to write down like x stat i have. i want like loop through my stats, and do this for all of my stats

#

something like that, sorry bad english

#

but as i said maybe im just overcomplicate this and write 3 lines of code and thats it

eternal needle
teal viper
#

Sounds like you want an array/list

#

Or a dictionary

eternal needle
#

really depends what you're trying to do with this also

regal bear
#

yea something like that

grave sage
regal bear
#

Now my exact problem is, i have a decreaseStat() function, its do the math / second, for every stat and decrease it by a number, each one different. And when for example my character is in the toilet, i want to stop but only the Needs stat to decrease, and start increase. I just put booleans for each stat like isRegen? and if false, then do the decrease, if not, then stop the decrease and in other function i start regenerating

#

I guess this code is a mess:

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Toilet"))
        {
            IsNeedsRegen = true;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Toilet"))
        {
            IsNeedsRegen = false;
        }
    }

    public void decreaseStat()
    {
        fatigue -= fatigueSpeed / 60;
        fatigueBar.SetValue(fatigue);

        hunger -= hungerSpeed / 60;
        hungerBar.SetValue(hunger);

        thirst -= thirstSpeed / 60;
        thirstBar.SetValue(thirst);

        if (!IsNeedsRegen)
        {
            needs -= needsSpeed / 60;
        }
        else if (IsNeedsRegen)
        {
            increaseNeeds();
            //Debug.Log("Increasing Needs");
        }

        needsBar.SetValue(needs);

    }
#

but maybe its fine idk

#

decreaseStat() fires in every second

#

btw im only tried to implement this to Needs, thats why i have this only here

eternal needle
# regal bear but maybe its fine idk

well the code is definitely questionable. having lists or dictionaries for the stats can help clean things up. A list for the fatigue, hunger, thirst, and possibly another list for the speeds. Though I find it odd you are doing fatigueSpeed / 60, seems like quite a magic number used there.
Also this OnTriggerEnter2D logic is gonna be quite the nightmare in the future if you start to implement more and more. It would make more sense if this script was on the objects that actually give the buff or debuff. this is also gonna be a bit more complicated so consider how large you want this project to be

regal bear
#

i want simple as possible

#

but clean, effective code

#

i just have 4 stats, and i don't want to add more, but i tought good idea to create like a generic stat scripts, and then maybe reuse this for future projects

#

so the functions can work with 1 stat, 4 stat or maybe 10 idk just sayin

teal viper
regal bear
#

just got the idea i don't know if its good or not, if i decrease my hunger with 10, and i want to icrease it with 20, i just increase it with 30 so the minus 10 still works, but i overwrite it with the icrease

regal bear
teal viper
hallow sun
#

so something like this?:

public ProgressBar[] bars;
public float[] variables;
public float[] speeds;

private void OnTriggerEnter2D(Collider2D collision)
{
  if (collision.gameObject.CompareTag("Toilet"))
  {
      speeds[3] = 0; // #3 is Needs
  }
}

private void OnTriggerExit2D(Collider2D collision)
{
  if (collision.gameObject.CompareTag("Toilet"))
  {
      speeds[3] = x; // whatever the default value is, perhaps on another variable?
  }
}

public void decreaseStat()
{
  for (int i=0; i<4; i++)
  {
    variables[i] -= speeds[i] / 60;
    bars[i].SetValue(variables[i]);
  }
}```
regal bear
# teal viper Might want to go learn C# properly before proceeding.

thats why im asking you, i hate school cuz the teacher just explain things for like 20 30 40 min, and we did nothing, I want to learn c# on the go, with small project, ofc my game never will be sellable or playable or anything, i just got a game idea and try to do it, and then learn on the road.

regal bear
hallow sun
#

instead of using bool just set the speed from zero/the speed

teal viper
bronze surge
#

Does anyone here know to invite someone to your unity project? nothings been working

eternal needle
regal bear
eternal needle
hallow sun
eternal needle
abstract finch
#

Why am I unable to modify a public float within this struct? The error goes away if I turn the struct into a class.

            {
                _actionInfos[i].TimeUntilAvailable -= Time.deltaTime;
            }```
 error CS1612: Cannot modify the return value of 'List<CharacterActionInfo>.this[int]' because it is not a variable
abstract finch
#

thanks

bronze surge
tiny hawk
#

Can anyone help me debug why a script on one of my game objects it not being called? I have Debug.Log in the start and awake, but neither are being called. The script is enabled on the game object.

#

I put the script on a tree that's being called by the terrain system

#

It gets called when not using the terrain system

eternal needle
tiny hawk
brave compass
abstract finch
#

actually I need them it to be a list unfortunately

mystic pike
#

how do i change the pivot point of a 2D object?

rich adder
#

or UI has the rect transform

mystic pike
#

thanks

mystic pike
rich adder
mystic pike
rich adder
#

idk what that means

magic panther
#

!code

eternal falconBOT
magic panther
#

I am making a game that's sort of a sokoban. So far I have player movement and when you walk into a wall, if possible, it will run it's interact function. We also have a crate, which is a wall I'd like to push. The issue being that I'd like this to chain with other crates no matter the ammount. That means, I need someone to help me make a system of checking if the wall in front can move.

How I'd imagine this:
Player interacts with crate -> Crate gets the player's moveDir -> Crate checks in moveDir direction for obstacles -> If none, proceed to move and return true to let the previous crate/player move -- If something is encountered, check if it's a crate -- If yes, ask it to check further.

https://hatebin.com/jsrwjlvtpn << Player Script
https://hatebin.com/mpqqqfzmep << Wall Script
https://hatebin.com/qnerftymbo << Crate Script

The biggest issue with this I see is we need some way to check for crates without using a string variable like wallType. If it's a crate, it has a special function that returns a boolean and grabs the moveDir as an argument. This would chain nicely and stuff.

Does anyone have an idea how I could make all this work?

#

I think I'm overcomplicating a bit

#

Most important: How can I check if the detected object is a crate

untold patrol
#

Hi currently trying to work on animations for opening and closing doors. i have a scipt and animations all setup which work in the preview and show the interaction working. i know the code works on another type of door but for some reason isnt working with this, if anyone can help that woudl be great thanks.

wary igloo
magic panther
stray pivot
nimble apex
#

this is totally pointless right?

    public virtual void OnClose()
    {
        if (this != null && this.gameObject.activeInHierarchy)
        {
            StartCoroutine(OnCloseFlow());
        }
        else
        {
            OnCloseFinish();
        }
    }
    private IEnumerator OnCloseFlow()
    {
        OnCloseFinish();
        yield break;
    }```
#

im fixing codebase

#

i guess i just gonna do onclosefinish directly

blissful spindle
#

Hi, I don't know if this is the right place to ask but I wanted to make guns in my game aimable but I did it by using Quaternion.Lerp so the gun couldn't do things like bobing because it was affected by my lerp to go to a specific position when holding RMB, so I wanted to ask what is the right way to implement aiming into a FPS game

nimble apex
teal viper
blissful spindle
fringe plover
#

Will OnApplicationExit work on android?

topaz mortar
#

I'm calling UGS CCM like this:

public Dictionary<string, object> FightSomeMonsters(IExecutionContext context, IGameApiClient gameApiClient, int killedmonsternumber)
{```
How would I save the context and gameApiClient globally so I don't have to pass it to other functions/classes that get called?
They're injected through dependency injection when calling a cloud function
I would need them for every Cloud Code Function I call too
regal bear
#

Hello, im total beginner with coding, learned a bit but not much, trying to create my first project, i wrote a stat script for player (hunger, thirst etc.) but was a mess, now i refractored my code, i think this looks nice, maybe a bit overcomplicated, but want clean and flexible code, i think this is a good start. I call handleAllStat() in a different script, when i wrote my ingame time, so its called in every IRL seconds. Please say if its too bad, or anything. https://gdl.space/cefevivuko.cs

ivory bobcat
#

Maybe less usage of static members and a struct data type that holds these grouped together {max, current, decrease, increase}.

regal bear
regal bear
gaunt ice
#

then learn how to reference an instance correctly

ivory bobcat
regal bear
# gaunt ice then learn how to reference an instance correctly

what you mean? I want to use a variable in a same script, and i can't cuz "A field initializer cannot reference the non-static field, method, or property 'PlayerStats.decreaseHunger'" I looked your link, but still don't know where to search, cuz its not from other scene, or from prefab, asset, or children prefab.

slender nymph
#

that's because you assign to fields using other fields in the field initializers. it forces you to make things static unnecessarily which will cause further issues later on. don't make those variables static. and assign them to your other variables inside of a method like Start or Awake

#

you should also make non-static variables of your Stat type so you can serialize them instead of setting them up manually using half a dozen other fields

gaunt ice
#

or using awake/start

regal bear
#

okay i guess i start to understand, can you link some example code?

gaunt ice
#

don't make those variables static. and assign them to your other variables inside of a method like Start or Awake
from boxfriend

regal bear
gaunt ice
#

yes, and prevent hard coded number (magic number)

int x=10;
-->
const int LEFT_BOUND=10
int x=LEFT_BOUND;
languid spire
burnt vapor
#

It was probably related to the code where things like
currentValue -= decreaseValue / 60;
Are written, where you should probably use a constant instead

languid spire
#

I don't disagree with the rational, just saying it 'prevents hard coded number'

regal bear
burnt vapor
#

I think magic numbers are not as interesting to fix over magic strings, but still it would be nice considering you appear to write it multiple times and it helps understanding why it is 60 when you come back to it after a while

languid spire
#

I think the most important thing to know about magic numbers or strings is to define them only in one place so that if it changes it changes for ALL usages

regal bear
languid spire
regal bear
#

I dont know how to pair my stats with my stats slider on my UI. I tought use serializefield and drag n drop the bar to a stat is a bad practice

wooden sandal
#

i suddenly get a null ref exception on an event... how is that possible?

regal bear
#

So my last question is for now, is drag n drop things to the inspector a bad practice? So should i get objects or anythings in code, or using the inspector with drag n drop is a good way too?

languid spire
regal bear
languid spire
eternal falconBOT
regal bear
#

Oh thats a good thing, cuz using the inspector is way easier haha

wooden sandal
#

this is my event delegate

        public delegate void PopUpRequest(string text = null);
        public static event PopUpRequest OnPopUpRequest;

This line calls it

        private void RequestPopUp(string text = null)
        {
            OnPopUpRequest(text);
        }

this is the error msg

#

it tells me the event itself is null... i am confused

languid spire
#

try

OnPopUpRequest?.Invoke(text);
wooden sandal
#

yeah it seems its the case. but that only fixes the error msg. how is it even possible that the delegate was not created?

languid spire
#

because no one has subscribed to it

wooden sandal
#

holy shit, i found the problem... the subscriber would be disabled just before the request... oh boy...
thanks for the help

heavy geyser
#

Hello I was hoping if someone could help me figure out how to get two functionalities working for my little frogs. I have them moving around the scene and whenever they are standing still I want them to have a low chance of either blinking, or croaking. However, I can not get this to work. This is because in order to determine when I should croak or blink I am doing stuff coroutines that are being called in the update function. This causes the frog to freak out and be constantly croaking or blinking. Which is painful to see, and hear.

Here is my code:

     void Update() {
        Movement();

        int x = 0;
        if (x == 0) {
            StartCoroutine(Blink());
            x++;
        }

        int y = 0;
        if (y == 0) {
            StartCoroutine(Croak());
            y++;
        }

        if (Random.value < croakProbability) {
            if (!_isCroaking && !_isBlinking && !_isMoving) {
            }
        }
    }

void Movement() { }

    IEnumerator Blink() {
        yield return new WaitForSeconds(Random.Range(6.0f, 24.0f));

        _isBlinking = true;
        Debug.Log("Blink");

        _animator.SetBool("isBlinking", true);

        yield return new WaitForSeconds(0.5f);
        
        _animator.SetBool("isBlinking", false);

        _isBlinking = false;

    }

    IEnumerator Croak() {
        yield return new WaitForSeconds(Random.Range(16.0f, 32.0f));

        _isCroaking = true;
        Debug.Log("Croak");

        _animator.SetBool("isCroaking", true);

        float pitch = Random.Range(minCroakPitch, maxCroakPitch);
        _audioSource.pitch = pitch;
        _audioSource.PlayOneShot(_croakSound, 0.75f);

        yield return new WaitForSeconds(_croakSound.length);

        _animator.SetBool("isCroaking", false);
        _isCroaking = false;
    }
#

The int x == 0 / int y ==0 was part of an experiment i know it looks very weird and shabby

keen dew
#

Start the coroutines once in Start and put the contents inside a while(true) loop

heavy geyser
#

lemme try UnityChanSalute

#
    private void Start() {
        _rb = GetComponent<Rigidbody2D>();
        _audioSource = GetComponent<AudioSource>();
        _animator = GetComponent<Animator>();
        _spriteRenderer = GetComponent<SpriteRenderer>();

        StartCoroutine(Blink());
        StartCoroutine(Croak());
    }

    IEnumerator Blink() {
        while (true) {
            yield return new WaitForSeconds(Random.Range(2.0f, 6.0f));

            _isBlinking = true;
            Debug.Log("Blink");

            _animator.SetBool("isBlinking", true);

            yield return new WaitForSeconds(0.5f);
        
            _animator.SetBool("isBlinking", false);

            _isBlinking = false;
        }
    }

    IEnumerator Croak() {
        while (true) {
            yield return new WaitForSeconds(Random.Range(16.0f, 32.0f));

            _isCroaking = true;
            Debug.Log("Croak");

            _animator.SetBool("isCroaking", true);

            float pitch = Random.Range(minCroakPitch, maxCroakPitch);
            _audioSource.pitch = pitch;
            _audioSource.PlayOneShot(_croakSound, 0.75f);

            yield return new WaitForSeconds(_croakSound.length);

            _animator.SetBool("isCroaking", false);
            _isCroaking = false;
        }
    }```

Hmm now they're not blinking or croaking at all. It maybe worth mentioning that the scene these frogs are in is added additively, and deactivated along side its gameobjects if that makes any sense, or any help at all
languid spire
heavy geyser
#

i'm no longer using that atm, I am starting the coroutines in the Start function now like Nitku suggested

keen dew
#

I'm not quite sure what you mean that the objects are deactivated? At what point does that happen?

heavy geyser
#

hang on just reloading unity back up, PC crashed

#

I have a primary scene, MainScene which, at the start of the game, will additively load a list of scenes. These scenes are then set to not being active, and then all of the gameobjects within those scenes are deactivated. The scenes and gameobjects within those scenes and then reactivated when I "travel" there

#

I do not believe this is part of the issue as the frogs do spawn and activate correctly, I just thought it might be worth a mention

keen dew
#

Do you see the debug.log messages in the console?

heavy geyser
#

I do not

keen dew
#

Any error messages?

heavy geyser
#

No, nothing

keen dew
#

Just as a sanity check, if you put a log in Start after the StartCoroutine calls, do you see that?

heavy geyser
#

Yes okay, so it does print that it's blinking and croaking, but thats when the game first starts up and the split second before the scene is deactivated

keen dew
#

If the scripts are on an object that gets deactivated it'll stop the coroutines as well

heavy geyser
#

hmm that makes sense

topaz mortar
#

Wow, I refactored my server to just use JsonConvert.DeserializeObject and JsonConvert.SerializeObject from working with Dictionaries within Dictionaries within Dictionaries
It's SO much easier and clearer now 😮
Thanks for all the good advice in here 🙂

#

<@&502884371011731486>

heavy geyser
strong wren
#

!collab

eternal falconBOT
keen dew
heavy geyser
#

That worked, thank you @keen dew

willow pike
#

Hello, can someone help me with these errors?

#

I don't get why Bitmap wouldn't be correct

topaz mortar
willow pike
topaz mortar
#

if it's from a package you installed it should be included or explained in that package

keen dew
#

Bitmap isn't a thing that exists in Unity by default. Why are you trying to use it and where did you get the idea that it would exist?

topaz mortar
keen dew
#

Ok cool but that doesn't tell me anything or answer the question

willow pike
#

And someone was helping me maek it, and they said to use bitmap

keen dew
#

well they were wrong

topaz mortar
#

Show us your IDE please

#

that would be the program you use to write code

willow pike
topaz mortar
#

screenshot your full screen with your mouse hovering over the error

willow pike
languid spire
topaz mortar
#

Visual Studio, not Unity

#
if (combatLog == null && combatLog.CombatLogLines.Count <= 0)
{ 
    TownController.Instance.EnterTown();
    return;
}

// Set current combat log line
CombatLogLine currentLine = combatLog.CombatLogLines[0];```
How am I getting this error on the last line?
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
languid spire
#
if (combatLog == null && combatLog.CombatLogLines.Count <= 0)

????????????????

topaz mortar
#

yeah? it returns if either is true so the last line can't get executed?

#

ah fuck &&

#

thx

languid spire
#

how can you have == null and then check a component of it ?

topaz mortar
#

should be ||

languid spire
#

no should be != null

topaz mortar
#

no I need it to return if it's null

languid spire
#

ok

topaz mortar
#

is that not a good thing to do?

languid spire
#

no, that's ok

#

I mean Count can never be < 0 but ...

topaz mortar
#

ah k

willow pike
gaunt ice
#

!ide

eternal falconBOT
gaunt ice
#

btw why your world creation need buffer

keen dew
#

Where did you get this script?

languid spire
willow pike
languid spire
willow pike
#

How do i configure it

topaz mortar
eternal falconBOT
languid spire
#

Did you miss the bot message a little above?

willow pike
topaz mortar
#

Visual Studio

languid spire
willow pike
#

No, i mean

topaz mortar
languid spire
topaz mortar
#

that easy to see huh?

languid spire
#

yep

topaz mortar
#

what about this one?

languid spire
#

like everything, if you wtf you are doing, everything is easy

tough cave
#

How do i reset the location in the middle of the text obect? I resized it to a smaller object, but now the things with the arrows is all weird and very height up above the actual object.. which is uncomfortable. Idk what its called.

languid spire
topaz mortar
languid spire
abstract finch
#

Whats the term called when the Y axis position of a camera adjusts depending on the vertical rotation? Is it gimbal lock? An example would be an over the shoulder camera

abstract finch
#

wow chatgpt is good

topaz mortar
#

it is lol

#

free too

abstract finch
#

is that browser based?

topaz mortar
#

and answers faster than peopl here 😛

#

yes

ebon robin
#

use gemini, plainly better

abstract finch
#

idk how to ask it but im trying it now for the math formula mentioned about pitch and vertical rotation

topaz mortar
#

just ask it like you would here

#

UGS just responded to my client request from my server in 7ms?

abstract finch
#

yea im figuring out how to ask im thinking along the lines of:
How would I be able to maintain a consistent pitch of an over the shoulder camera while adjusting the vertical rotation?

#

public class OverShoulderCamera : MonoBehaviour
{
    public Transform target; // Reference to the player character
    public Vector3 offset = new Vector3(0f, 2f, -5f); // Offset from the player's position

    void LateUpdate()
    {
        if (target == null)
            return;

        // Calculate the desired position for the camera
        Vector3 desiredPosition = target.position + offset;

        // Smoothly move the camera towards the desired position
        transform.position = Vector3.Lerp(transform.position, desiredPosition, Time.deltaTime * 5f);

        // Make the camera look at the player's position
        transform.LookAt(target.position);
    }
}```
I'm giving it a ago but I dont think its what I want lol
topaz mortar
#

Must be some new predictive AI or something

#

did it like 100 times, every other time was 150+ lol

languid spire
abstract finch
#

it doesnt work at all unfortunately

languid spire
#

in fact it 'knows' nothing so I'm not surprised

abstract finch
#

idk how to describe it, it just doesnt work lol

languid spire
#

and you don't know enough to figure out why. Which is why GPT code is frowned upon in this server

burnt vapor
eternal falconBOT
#

:teacher: Unity Learn ↗

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

dim brook
#

not a code issue but how do i get rid of this

languid spire
dim brook
#

doesnt really seem to have a help channel on this idk

languid spire
#

you have not even bothered to say what 'this' is, how can you expect help? And keep it in the correct channel

willow pike
languid spire
willow pike
languid spire
#

Still NOT configured
this should read Assembly-CSharp

languid spire
# willow pike

Right click on the project (in the solution explorer) and select reload with dependencies

strong wren
#

How are you ending up with this packet code anyway?

hidden heath
# willow pike It configured

It's not hard to set up Unity with Visual Studio. It also helps with code. You still gotta know what you're doing though.

hidden heath
hidden heath
topaz mortar
hidden heath
#

Mr. Pasc. Don't make me hunt you down and watch C++ tutorials. The reason thats torture is because this is Unity not Unreal.

hidden heath
#

Just busy with my own stuff eh?

fickle plume
#

Keep it on topic, please.

hidden heath
#

Plus i'm tired and just woke up so I ain't im the best mood. Canadian weather is too warm right now.

static cedar
hidden heath
fickle plume
#

@willow pike Make sure the file is in the assets and open it from Unity

willow pike
#

But i still get that error

languid spire
proud heath
#

Why doesn't it work

deft grail
#

you arent using rotation

proud heath
#

I mean why is the Euler red

deft grail
#

because it should be Vector3 rotation =

#

read the error

proud heath
#

Cannot resolve symbol 'Euler'

verbal dome
#

That code looks ok to me

modest dust
deft grail
#

oh yeah, you just pass a Vector3 inside it, i forgot because i havent used it in a while

proud heath
#

'Quaternion' does not contain a definition for 'Euler' I already googled it and didn't find much

verbal dome
#

I dont remember ever seeing a 'cannot resolve symbol' error 🤔

verbal dome
proud heath
#

should be that one

brave compass
#

It's probably System.Numerics.Quaternion.

verbal dome
proud heath
#

uhmm how can I check

verbal dome
#

Hover your mouse on Quaternion

brave compass
#

If you have using System.Numerics; and no using UnityEngine;, or if you have both and using Quaternion = System.Numerics.Quaternion;

proud heath
#

It says System.Numerics

#

all good it works now

willow scroll
wintry quarry
#

Don't they want the Unity one?

#

Just get rid of all mention of System.Numerics

willow scroll
#

So they might want it?

wintry quarry
#

Yeah they meant it said that before and now they deleted it

#

Use context clues

wintry quarry
main anchor
willow scroll
#

Right, I have just read the last 2 messages

wintry quarry
#

That's a function on the UnityEngine version

willow scroll
verbal dome
#

I see it stuttering up and down on the ground a bit, is that it?

#

Is it like sinking into the ground?

willow scroll
#

The playerHeight is assigned in the Inspector, even though you may access the player's height via player.transform.localScale

#

Additionally, the offset 0.2 is added

#

And it's better to check with the OnCollisionEnter & OnCollisionExit methods

magic panther
queen adder
#

i got this error i was trying to import this from github, its a vhs style camera, it was working at the begenning but i dont know i did and now it doenst work, i tried to delete all, but the error persist's

short hazel
# magic panther If someone's got a moment, please tell me how to do this

Try to get the crate script on it:

if (obj.TryGetComponent(out Crate crate))
{
    // it's a crate. Use the 'crate' variable which is a reference to the crate script.
}

Or since it inherits from the Wall class, and you already have a variable of type Wall, then you can type-check it
if (wall is Crate crate)

main anchor
buoyant knot
#

your character has weak knees

#

it really depends on what sort of physics you have. ie kinematic, dynamic, or KCC

#

it sounds to me like a kinematic rb that doesn’t calculate the position of the floor properly

tough cave
#

how to tell if a object (player) is going down?
I google and one says
if (rigidbody.velocity.y < 0)
This isnt checking if the position fo it is below 0 of y axis?

short hazel
buoyant knot
#

this will tell you nothing about where your RB currently is

short hazel
#

Either _material or _player (or both) don't have a value

#

Make sure there's a VideoPlayer on the same object as this script

buoyant knot
#

you might want to crack open the Debugger to check the values of the variables around that point in code

short hazel
#

Maybe you attached the script somewhere else by accident, and it's the other one throwing errors

#

Search for t: GlitchEffect in the Hierarchy

queen adder
#

when i press it goes to camera

ebon skiff
short hazel
#

Ah it's a different class name than what's shown in the Inspector

#

VHSPostProcessEffect

queen adder
#

so what i should do?

#

i am sry i new in unity

short hazel
#

Search for that in the Hierarchy

queen adder
short hazel
#

Select that, and make sure there's only one instance of that script attached to this object

queen adder
#

Hello, could anyone help me with this issue? Thanks.

languid spire
burnt vapor
eternal falconBOT
burnt vapor
#

Then we help

queen adder
#

oh

#

i misspeled

short hazel
# queen adder

Apply the changes to your player prefab (button at the top of the Inspector labeled "Overrides") and try again. If this fails, you'll have to perform basic debugging steps to see where the problem is.

burnt vapor
stoic glen
#

Why does a Raycast hit an Object with the Layer 6, even if the layermask excluded Layer6

short hazel
# queen adder it was alredy on that

No you added components (which are shown with a green "+" icon on their Inspector icon, and blue bars on the left - for example the scale has been changed), so these must be applied to your prefab. The one you have in your scene is a copy

#

And yes, that is the correct button, click it and select "Apply all"

short hazel
#

Don't expect it to work by passing 6 to the Raycast, for example

stoic glen
queen adder
#

but the error apears

short hazel
languid spire
short hazel
#

The easiest is to make that variable public and set it in the Inspector directly!

stoic glen
short hazel
#

6 in binary is 1100

queen adder
stoic glen
stoic glen
short hazel
#

That's how the masks work, one bit for each layer. When that bit is 1, include, else ignore

languid spire
short hazel
# queen adder

Follow basic debugging instructions pinned to this channel:

cursive wraith
#

Is there any way to update an AudioClip on a AudioSource, but so that it keeps playing at the most recent timestamp?

#

Kinda like changing the AudioClip in place

queen adder
short hazel
#

Then you might need to take a step back and follow a programming tutorial

#

!learn has a lot of them

eternal falconBOT
#

:teacher: Unity Learn ↗

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

short hazel
#

I'd advise learning barebones C# without Unity though, as it's simpler to understand

magic panther
magic panther
#

I mean this

#

wait a sec

#

ill show what I meant

slow dagger
#

Hello yesterday i was doing the game without any errors and today just popped 33, i dont understand what the error means can somebody help? thanks in advance

magic panther
#

wait no I forgot I had an if statement ready there

wintry quarry
magic panther
#

lemme test first before I yap

surreal basalt
#

hey

#

im getting error when i build the game

ivory bobcat
surreal basalt
#

its android

magic panther
languid spire
lilac hemlock
#

my list in my SO looks like this. Does anyone know how you can troubleshoot this?

languid spire
queen adder
#

I created a slider, that slider is my stamina bar, and he was a straight bar, but i applied a vhs style for my camera, and the bar is no more straight, because of the things i added, it possible to make straight again?

lilac hemlock
languid spire
eternal falconBOT
languid spire
lilac hemlock
languid spire
# lilac hemlock

Ok, you you are using ODIN, you might have mentioned that, and why are you not asking in their Discord?

lilac hemlock
#

It is the list that is not working

languid spire
#

But the whole SO object is controlled by Odin not just the Dictionary

lilac hemlock
languid spire
#

Ok, so the code of StatBase?

languid spire
lilac hemlock
#

i forgot that i changed accessability

short hazel
#

And it has a custom constructor so it might fail to be instantiated properly

lilac hemlock
#

and then i am wondering why nothing works

#

sorry, my bad

#

thanks

languid spire
lilac hemlock
#

all works now

magic panther
magic panther
languid spire
magic panther
#

no, so what?

languid spire
#

Spamming the channel

magic panther
#

wouldn't call this spam but alright mate

short hazel
#

ie. obj is OtherObject

magic panther
#

so then it'd be for a quick check

#

that's really useful, thanks

spare magnet
#

hello there!( i am working on a 2d game)
how big should i make my level,like whats the logic here
should i make the whole map in a single scene(adjusting everything by making everything smaller hence it will fit) or should i divide it
even if i am dividing it how big the division should be.Even an estimate would suffice
i know its a stupid question but i want to know the logic behind it .Thanks!

queen adder
#

Tell me, who is rummaging around, connected Npgsql to Unity (Nuget package for connecting PosgreSQL) and after that all Unity methods turned red IDE writes that there seems to be an error, but the code works in Unity

#

Before this, Unity was connected to visual studio

short hazel
#

Restart Visual Studio. Note that Unity does not support NuGet and will reset your project configuration at each restart.

languid spire
short hazel
#

If you have a .nupkg file, then you can extract the DLLs by opening the file as a .zip file

#

They are just zip files with another extension

eternal falconBOT
abstract finch
#

I dont know how to ask this but is there a way to get the direction of a current velocity thats relative to where the player is facing? I need this in order to plug in the Horizontal and Forward vectors into the animator for locomotion.

wintry quarry
languid spire
abstract finch
keen needle
#

I have this code that makes a parabola with raycast to simulate the trajectory of a bullet in real time, but I have to raise the fixed time steep a lot and the performance is very bad, any ideas to improve it?

eternal falconBOT
keen needle
#

I don't know how to use it

willow scroll
wintry quarry
queen adder
#

Do you know how you can connect PostgreSQL to Unity using native methods?

wintry quarry
#

Use a link to a paste site like it says please @keen needle

queen adder
willow scroll
keen needle
#

more than 2k characters

wintry quarry
willow scroll
wintry quarry
short hazel
keen needle
fervent abyss
#

how can i draw custom editor stuff ABOVE main script variables?

wintry quarry
#

that's 100 seconds worth of physics simulation

willow scroll
wintry quarry
#

Also you need to cache th9ings like LayerMask.NameToLayer("Suelo") @keen needle

#

Additionally rather than doing lineRenderer.positionCount++; in each iteration, you can set the position count one time at the start

#

since you know how many points you'll be generating

keen needle
wet heath
#

Anyone got any links to or know of any good tutorials on making a slightly more advanced fps ammo system? (maximum ammo, current ammo, etc.)

queen adder
#

Ok th guys

willow scroll
wet heath
keen needle
wintry quarry
wintry quarry
wintry quarry
polar acorn
#

It's just two variables

wet heath
wet heath
#

Idk, man, just like any basic tutorials on an ammo system out there. I've found nnone that would help me :[

polar acorn
wintry quarry
#

"ammo systems" are generally very simple, it's really not something you typically spend a whole tutorial on or something

#

it's just basic arithmetic generally.

polar acorn
#

It's just storing one variable and comparing it to another variable

wintry quarry
#

I suspect your real struggle is not being comfortable with handling data and programming in general

wet heath
#

I've been having trouble figuring it out, dumbass brain of mine

wintry quarry
#

What are you having trouble with?

wet heath
#

Hmmn

wintry quarry
#

Maybe share what you tried and what's going wrong

polar acorn
#

Another tutorial is just going to give you the same information you're already not getting, so why not ask the specific question and potentially get over whatever's blocking you

willow scroll
summer stump
fervent abyss
# willow scroll Looking fine to me. How do you draw it?
PlayFabManager playFabManager = (PlayFabManager)target;

        EditorGUILayout.TextField("PlayFab ID", playFabManager.PlayFabID);
        EditorGUILayout.TextField("PlayFab Username", playFabManager.PlayerDisplayName);
        
        if(DrawDefaultInspector()){

        }
wet heath
#

Well, it's something along the lines of:

  • Maximum Ammo
  • Current Ammo
  • Reserve Ammo

If reloading gun, ammo will be taken from Reserve Ammo, filling up Maximum Ammo. If none left, do nothing

Basically

polar acorn
summer stump
wet heath
#

The problems I've faced have been all over the place, like the math is all wrong. I dunno if it's wise to chuck a bunch of my shit code in here or not, i don't wanna have to bother everyone too much

fervent abyss
wintry quarry
#

"the math is all wrong" what math?

#

In what way was it wrong?

wet heath
#

Ok but I am a beginner ofc

summer stump
eternal falconBOT
wet heath
#

Maybe we should use threads then

wintry quarry
wintry quarry
summer stump
ivory bobcat
fervent abyss
summer stump
bold nova
#

Does anyone know why scriptable object might not save changes even after being set to dirty? I try to save all enemy position in a dictionary off playmode. SO has just one method and it works fine, but as soon as i try to get the results during playmode dictionary ends up empty...

public Dictionary<Type, List<Vector3>> layout = new Dictionary<Type, List<Vector3>>();

[ContextMenu("Save current enemy layout")]
public void SaveCurrentLayout()
{
    layout.Clear();

    List<Enemy> enemies = new List<Enemy>();

    enemies = GameObject.FindObjectsOfType<Enemy>().ToList();

    if (enemies.Count == 0)
        Debug.LogError("No enemy found on the scene.");

    foreach(Enemy enemy in enemies)
    {
        if(layout.ContainsKey(enemy.GetType()))
        {
            layout[enemy.GetType()].Add(enemy.transform.position);
        }
        else
        {
            layout[enemy.GetType()] = new List<Vector3>();
            layout[enemy.GetType()].Add(enemy.transform.position);
        }
    }

    EditorUtility.SetDirty(this);
}
stoic glen
#

How can I delete an script. When I use
NewBehaviourScript nbsTemp = tempObject.GetComponent<NewBehaviourScript>(); Destroy(nbsTemp);
The script gets disabled, but the functions are still working, because of inheritance.
How can I remove it, during runtime?

polar acorn
#

That will destroy that instance of that component on that object

stoic glen
polar acorn
#

If you're not seeing it being destroyed then either:
A) That is not the object you're destroying in code
B) Something else is putting it back

final totem
#

is visual scrpting commonly used in unity or it suck/csharp better?

summer stump
#

Like all visual scripting. Well, some things benefit from it. Animator, shader graph, etc

polar acorn
# final totem is visual scrpting commonly used in unity or it suck/csharp better?

Visual Scripting is specific to Unity, changing rapidly, and is almost entirely used by non-programmers. This makes it actually harder to learn visual scripting than C#, which has a monumental amount of learning material made by the people who understand it for unity and non-unity uses, and very little of it ever becomes "obsolete"

#

Visual Scripting suffers from the "Ketchup Packet Problem" which is that the people who make it never actually use it. C# references and libraries are made by C# programmers for C# programmers, so there's a bit of an incentive to make it sensible. Visual Scripting is made in code for people who will never use code, so the people making it have no reason to actually use it to determine if it's good or not

rich egret
#
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;

public class RoomsList : MonoBehaviourPunCallbacks
{
    public RoomItem roomItemPrefab;
    public Transform _content;
    public List<RoomItem> roomItemsList = new List<RoomItem>();

   public override void OnRoomListUpdate(List<RoomInfo> roomList)
   {
        UpdateRoomList(roomList);
   }

   void UpdateRoomList(List<RoomInfo> list)
   {
        foreach (RoomItem item in roomItemsList)
        {
            Destroy(item.gameObject);
        }
        roomItemsList.Clear();

        foreach (RoomInfo room in list)
        {
            RoomItem newRoom = Instantiate(roomItemPrefab, _content);
            newRoom.SetRoomName(room.Name);
            roomItemsList.Add(newRoom);
        }
   }
}```

The `OnRoomListUpdate` function does not work for some reason
rugged sail
#

Hi! I'm a new Unity user and I was wondering if a "door option" such as Tarkov's would be viable to recreate in Unity. If so, how can I achieve this, and are there any resources online that can lead me towards it? ( I tried searching for it but it was mostly simple hinge-based physics doors and animation oriented doors, no mentions of the UI and how to implement it)

ionic plank
#

Hello, I have a problem with a scroll view (which is a scroll rect)
I have two differents code, one has the correct position at the end and one has the correct animation, and I want to have both ...

// The position is good !!!

    // void MovePage()
    // {
    //     Vector2 newPosition = new Vector2(targetPosition.x, levelPagesRect.anchoredPosition.y);
    //     levelPagesRect.anchoredPosition = newPosition;
    //     UpdateBar();
    //     UpdateArrowButton();
        
    // }

// The animation is good !!

    // void MovePage()
    // {
    //     Debug.Log("ici"+targetPosition);
    //     levelPagesRect.LeanMoveLocal(targetPosition, tweenTime).setEase(tweenType);
    //     UpdateBar();
    //     UpdateArrowButton();
    // }

short hazel
#

Tarkov is made with Unity, so that's definitely possible

polar acorn
rugged sail
rich egret
polar acorn
rugged sail
rich egret
short hazel
#

If you have issues with setting up the UI then you should ask in #📲┃ui-ux

polar acorn
ionic plank
rich egret
polar acorn
rich egret
#

And it just doesn't show up in "On Click"

polar acorn
crystal chasm
#

What's Updae?

rich egret
rich egret
polar acorn
ionic plank
#

Hello everyone,

I am having trouble with my Scroll Level View. This view is used to display all the levels that are saved in the game. I am unable to successfully move to the next page with an animation that goes to the correct position. However, I have been able to move to the correct position without the animation and I have also been able to do the opposite. Does anyone know how to fix my issue?

Thank you in advance for your help.

// The animation is good !!

    // void MovePage()
    // {
    //     Debug.Log("ici"+targetPosition);
    //     levelPagesRect.LeanMoveLocal(targetPosition, tweenTime).setEase(tweenType);
    //     UpdateBar();
    //     UpdateArrowButton();
    // }

// The position is good !!!

    // void MovePage()
    // {
    //     Vector2 newPosition = new Vector2(targetPosition.x, levelPagesRect.anchoredPosition.y);
    //     levelPagesRect.anchoredPosition = newPosition;
    //     UpdateBar();
    //     UpdateArrowButton();
        
    // }
spare magnet
#

is it ok if i am making my gameobject script with help of chatgpt
do developer do that?or should i figure it out on my own
(i know c# well but i dont know functions like get.key(code.space)
but i just bybass learning these function throught chat gpt)

polar acorn
spare magnet
#

sorry
Input.GetKeyDown(KeyCode.Space)

#

i was giving an example
like yeah i dont know the syntax of these function but throigh chat gpt i can make it work XD

polar acorn
#

Documentation is almost always top of the search for basically any question, and you dont have to worry about the documentation hallucinating functions that don't exist

ionic plank
#

Am I in the wrong place to ask my question ?

polar acorn
spare magnet
#

Cool thanks

wintry quarry
#

destroying a component:

  • Doesn't remove it from any lists
  • Doesn't remove any references you have to it.
rugged sail
rugged sail
dreamy junco
#

Is somebody able to answer a Unity related question?
I’ve modified Flappy Bird. I followed a tutorial by Game Maker’s Toolkit. He suggested adding pressure plates. Because I thought it was easier I only allowed the player to get a point, if it activated the pressure plate. When the player flies through the pipes, the possibility oft he player gettiing the point. Code followes.
private void OnTriggerEnter2D (Collider2D collision)
{
if (collision.gameObject.layer == 6)
{
plateActive = true;
Debug.Log("Treffer!");
this.gameObject.GetComponent<SpriteRenderer>().sprite = ActivePlate;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3 && active.plateActive && status.birdIsAlive)
{
logic.addScore(1);
active.plateActive = false;
Debug.Log("Punkt erzielt!");
}
}
The problem is that it seems to be random, when the player gets the point. The player activates the plate and flies through the pipe, but it doesn’t get the point. At the first pipe the player always gets the point, if the plate is active. Then the player doesn’t get the point 3 times, then it almost workes and then it gets the point even though the plate isn’t even active.
Layer 6 is the arrow, and Layer 3 is the bird. The first script is owned by the plate and the second one by the middle of the pipe. And I read through the log, and it seems, like "plateActive" gets set to true, then it keeps beeing false and than it changes like every frame from false to true.

gaunt ice
#

!code

eternal falconBOT
umbral bough
dreamy junco
#

multiple

#

the first one is from the plate the second is from the middle of the pipe

umbral bough
#

ok, my advice, try using OnTriggerExit2D

#

look into it, that function gets called when you exit a trigger

#

so that way, you could set the active bool to false once you pass the pipe instead

molten dock
#

how do i have the game totally restart on player death

umbral bough
rugged sail
# dreamy junco multiple

maybe the OnTrigger2D is being called multiple times in a single frame, which causes the plateActive to switch true false true false true false. try adding a cooldown period after plateActive is set to true, so that it cant be set to false?

molten dock
#

yeah its a static issue i think

summer stump
umbral bough
molten dock
#

Okay

#

i can do dat

#

swag

summer stump
molten dock
#

yes

umbral bough
summer stump
# molten dock yes

For what? Because generally that is not good. Singletons should be fine

rugged sail
#

sumn like this?

umbral bough
#

look into singletons as suggested, they are quite useful

molten dock
#

i have a static for player health which i gotta acsess between scenes

#

have a static to detect stuns

summer stump
umbral bough
#

ok, reset that value on player respawn then

summer stump
molten dock
#

have a static i use to load scenes based on its value

umbral bough
#

you'll learn through practice when to use static vars

#

but they should generally be avoided when possible

#

but from your messages, it seems like you desparately need a singleton

molten dock
#

singletons look too complicated

umbral bough
#

infallible code has an excellent vid on it

umbral bough
rugged sail
umbral bough
#

and once you do, it'll feel awesome

eternal needle
#

If a singleton is too complicated, I got some bad news on how complicated full games are

molten dock
umbral bough
umbral bough
umbral bough
rugged sail
molten dock
#

what

rugged sail
#

why’s that eh

stone saddle
umbral bough
wintry quarry
stone saddle
#

yes

#

collision detection is also continuous

dreamy junco
#
    void Update()
    {
        if (timer <= 0.25f)
        {
            pipeCooldown = true;
        }

        else
        {
            timer += Time.deltaTime;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.layer == 3 && active.plateActive && status.birdIsAlive)
        {
            logic.addScore(1);
            active.plateActive = false;
            Debug.Log("Punkt erzielt!");
            timer = 0;
        }
    }
}

Now I’ve changed Enter to Exit and added a cooldown, but my problem is still the same.

wintry quarry
wintry quarry
dreamy junco
#

I told you about the problem earlier, scroll up.

stone saddle
# wintry quarry how is your camera follow working?

i have a pixel perfect camera and another simple one that i found online ```using UnityEngine;

public class CameraMovement : MonoBehaviour
{
public Transform target; // Reference to the player's transform
public float smoothSpeed = 4f; // camera smoothness
private Vector3 velocity = Vector3.zero;

private void FixedUpdate()
{
    if (target != null)
    {
        // Create a target position with the same x-coordinate as the player and the camera's current y and z coordinates
        Vector3 targetPosition = new Vector3(target.position.x, transform.position.y, transform.position.z);

        Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothSpeed);
        transform.position = smoothedPosition;
    }
}

}

wintry quarry
#

so obviously it will be jittery

summer stump
# molten dock singletons look too complicated

Singletons are super simple. But not necessary if you don't want. Either way, just get rid of all those static variables
They are completely unnecessary and harmful to your code in the way you are using them

stone saddle
#

the camera itself isnt jittery, but the player looks to be moving between pixels when moving at full speed

#

like its stuck between and the camera keeps switching between positions

wintry quarry
#

this absolutely belongs in LateUpdate

stone saddle
#

that makes sense, not sure why i left it like that

molten dock
stone saddle
#

do you know anything about the other issues?

molten dock
#

are u using deltatime

wintry quarry
summer stump
wintry quarry
#

but the player itself being jittery would be a consequence of not having interpolation enabled

wintry quarry
#

Namely TouchingDirections

stone saddle
#

most of the code in there was from a youtube tutorial, havent messed with it in a while#

molten dock
#

i thought that was you who told me to watch his video but naw

stone saddle
#

i changed it to late and made sure it was on interpolate (i just switched between the options to see what difference it made)

wintry quarry
# stone saddle

I would guess your problem is basically this:

IsOnWall = touchingCol.Cast(wallCheckDirection, castFilter, wallHits, wallDistance) > 0;```
You have some buffer distance `wallDistance` at which you detect the wall and then you probably stop moving. Rightfully you would want to probably teleport your character directly to be in contact with the wall or something at that point, or at least use the `distance` from the RaycastHit2D to move into the wall.
wintry quarry
#

is that running on FixedUpdate too?

stone saddle
#

public class ParallaxEffect : MonoBehaviour
{
    public Transform cameraTransform;
    public float parallaxFactor = 0.5f; // Adjust this value to control parallax effect strength

    private Vector3 startPosition;
    private float initialZ;

    private void Start()
    {
        startPosition = transform.position;
        initialZ = transform.position.z;
    }

    private void Update()
    {
        float parallaxOffsetX = (cameraTransform.position.x - startPosition.x) * parallaxFactor;
        float parallaxOffsetY = (cameraTransform.position.y - startPosition.y) * parallaxFactor;

        Vector3 newPosition = startPosition + new Vector3(parallaxOffsetX, parallaxOffsetY, 0);
        transform.position = new Vector3(newPosition.x, newPosition.y, initialZ);
    }
}
willow scroll
#

This is the Update method

stone saddle
#

i thought that the jittery-ness was a result of the pixel perfect camera

#

i mean

willow scroll
#

It's caused by not using Time.deltaTime

wintry quarry
#

This script shouldn't need any deltaTime, since it's directly driving the parallax based on the exact current camera position

#

it looks like it's designed to absolutely only happen after the camera position is determined though

stone saddle
#

yeah, i started this with absolutely no c# knowledge

willow scroll
#

Oh, right. It's just the offset being applied, but not constantly added

willow scroll
stone saddle
#

some things yes, other things from youtube tutorials

#

but i found the tutorials to be

#

not great

willow scroll
#

Alright, as PraetorBlue has said, put this into LateUpdate instead of Update

#

And you can make a Vector2 out of these paralaxxOffset floats

stone saddle
#

i think its still jittery but i cant tell if its because of the camera or not

molten dock
polar acorn
willow scroll
summer stump
stone saddle
molten dock
#

does not compute with me

polar acorn
#

It ties the data to a specific instance that can be serialized, disposed of, etc.
It lets you control the lifespan of statically accessible data as opposed to them just always existing no matter what

summer stump
#

Look at the singleton link in there

willow scroll
stone saddle
willow scroll
polar acorn
#

Static variables always exist. A static reference can be null, which means the object doesn't exist. Many types of data can't be null, and storing an int with a value of 0 takes as much space as storing one with a value of 2,147,483,647. A static variable needs to keep that allocated all the time. Would you rather one pointer to an object, or every single variable and property that object would otherwise have

stone saddle
#

its been changed to lateUpdate now

polar acorn
#

Singletons are considered an anti-pattern in general programming, but can be very useful in specifically game programming where you want as little data as possible to be persistent. It's still drastically better than just using static variables for everything

#

And if your alternative is having every single object use Find of some sort to get the instance to your object that would otherwise be a singleton, that is much worse than just using a singleton

dreamy junco
#

is there an easy way to avoid blur from scaled objects in unity

wintry quarry
wintry quarry
#

Maybe elaborate a bit?

#

also what does this have to do with code?

willow scroll
willow scroll
#

The camera shouldn't be jittering, right?

#

So that's the ParallaxEffect

dreamy junco
stone saddle
#

yeah i think the camera is fine now, but the player is still jittering between pixels

dreamy junco
#

and i wanted to showcase that the code doesn't work

wintry quarry
willow scroll
dreamy junco
#

it's blurred