#💻┃code-beginner

1 messages · Page 729 of 1

real ferry
#

And IDE

limber turtle
#

i use vsc

real ferry
#

It usally gives u a hint when Theres an Import missing

#

Iirc u need to import but i might be wrong

#

Lemme See rq

silver fern
#

you need using System.Collections.Generic; iirc

limber turtle
#

thank you

real ferry
#

Yes that one

silver fern
#

vscode should definitely tell you about that though

real ferry
#

Yeah

#

There should be a light bulb or Something in the line

#

But for unity i dont use vsc Just rider

limber turtle
#

no more red in my console

#

that's a sign

real ferry
#

Nice

silver fern
real ferry
#

Yep that one

grand snow
#

after a few years you just remember the namespaces

real ferry
#

ive only been doing unity for a month or something now rip

grand snow
#

thats what IDEs are for, they help you out

limber turtle
#

now it's getting mad about my right click input callbacks

real ferry
#

what is it saying

limber turtle
#

i think it's a null reference

grand snow
#

usually helps to share the error 😆

limber turtle
#

but idk what would be null

grand snow
#

!ide

radiant voidBOT
grand snow
#

setup your ide

#

coinScript is null

limber turtle
#

oh

#

oh shit i know what i did

#

the coin script is in the child of the prefab it's instantiating

real ferry
#

tbh imo its easier to get rider community edition cuz it has good support out of the box

limber turtle
#

i need to get the child for that stuff

real ferry
#

u dont need to get the child

#

if its a unique name u can just get it

grand snow
real ferry
#

i forgot the method 🤣

#

yes

limber turtle
#

thank you

#

i forgot about that

grand snow
#

do not find things with game object names

limber turtle
limber turtle
#

alright

#

i can place the coins and shoot them with my triangle

#

i shall save giving the coin physics for tomorrow

real ferry
#

nice

#

physics?

limber turtle
#

and for when i have added some test dummy enemy thing with infinite health

limber turtle
#

i wish for it to move

real ferry
#

u mean spin and float

#

ohh okay

limber turtle
#

and i'm thinking about making it so that you have more force when throwing it more horizontally but i'm not sure what i should use to do that

limber turtle
#

but if you've ever played ultrakill it's like that

real ferry
#

oh i only did 3d so far

#

so idk

limber turtle
#

2d is kinda just 3d but orthographic and everything is planar

#

unity is just strange

real ferry
#

yeah

silver fern
#

Thanks. It's looking good, but I'll finish writing it tomorrow

grand snow
#

why is effect duration cast to int 🤔

#

int/int will give you problems

silver fern
marsh canyon
#

Trying to make a main menu, and I already have the UI's setup with separate Canvas's for pages and all that... I even have a "First Selected Button" setup as well for when a Gamepad/Keyboard is last used.

However I am struggling with how to make it so button pressed = activate new Canvas and de-activate the other one.

grand snow
silver fern
grand snow
#

no

real ferry
#

i think yours will just cast effectduration

#

but the second casts the result

grand snow
#

my example casts the result of /

#

instead of casting EffectDuration to int, then doing /

silver fern
#

oh I thought / would return int

#

everything except EffectDuration is int already

real ferry
#

oh then maybe actually

grand snow
#

why restrict the duration to integers only?

#

0.5? fuck you its 1 now

polar acorn
#

Seems like this is a timer. Float would make much more sense for a timer.

silver fern
#

well my thinking is life points are always int and damage is always int so to count damage I should count in int

grand snow
#

thats dumb

#

you want to calculate the damage to apply per interval right?

silver fern
#

the damage per interval is EffectPower

#

and the interval is EffectFrequency

#

ig I should call it EffectInterval

grand snow
#

The better way to design it would be apply X damage every Y seconds Z times

silver fern
#

well I'm basically calculating z dynamically instead of having to pass another variable

grand snow
#

yea but there will be inaccuracy if you want to ensure some amount of damage is always applied as an int

#

anyway your choice

silver fern
#

I should probably add the variable tbh

#

yeah your way is better

edgy sinew
#

If I have some ability with a cooldown. Is using Invoke ( allowAbilityAgain, cooldown time ) bad practice?
Why do I see often online timeSinceThing += Time.deltaTime

silver fern
polar acorn
edgy sinew
polar acorn
#

There's basically three ways to handle timing things and they're on a sliding scale of convenience versus flexibility.
On the easy-but-inflexible side is Invoke, on the total-control-but-kinda-annoying side is a manual timer in Update, and in the middle somewhere are coroutines

grand snow
#

(dont forget async!)

silver fern
#

this should do, I can just return that from a method and use it to start a coroutine timer right?

grand snow
#

sorry what are you returning?

silver fern
#

the IEnumerator

real ferry
#

yield return null

#

after for loop maybe

edgy sinew
#

Like, “do ___ when coroutine ends”?

grand snow
#

hmm im not sure if you are doing something good

silver fern
#

uhoh

grand snow
#

StartCoroutine(DealDamage()) is the ideal way to start it
How do you plan to start it?

silver fern
grand snow
#

I dont see how that function is called from this

#

is there something in Effect? did you mean to have some virtual function each effect overrides?

silver fern
grand snow
#

yea but how do you plan to start all effects?

#
public abstract class Effect
{
  public abstract IEnumerator StartEffect();
}

something like this?

silver fern
#

I have ```CS
public abstract class ScriptableObjectEffect : ScriptableObject
{
public abstract Effect StartEffect(EffectContext context);

}```
and

public class Effect
{
    public int EffectPower;
    public float EffectDuration;
    public int EffectInterval;
    public int EffectRecurrence;
    public bool EffectIsDebuff;
    public int EffectAuthorityLevel;
}
#

actually the Scriptable Object class is abstract, not the Effect class, mb

grand snow
#

oh i see there is a so for each effect too

silver fern
#

yes

grand snow
#

but again how will the coroutine be started correctly on a mono?

edgy sinew
#

void useMagicWand() { all nearby enemies.effectReceiver += new BurnEffect(params) }

#

one option

silver fern
edgy sinew
#

nearbyEnemy[i].startEffect(magicWandBurnEffect)

silver fern
#

and when I did the first option people yelled at me

edgy sinew
#

yeah creating new stuff at runtime is not efficient

#

having stuff pre-configured and then “turn on or off” / “react to float value” is quicker i think

grand snow
#

oh no i allocated a new class instance the world is over!!!! /s

silver fern
edgy sinew
#

Modularity can still be intact. Youre using polymorphism already but

#

I’m just letting you know I had huge issues with the new keyword

grand snow
#

its fine unless done too much all the time

#

If so then you think about alternate designs to reduce allocation/gc

edgy sinew
#

Guy’s making an MMORPG no?

silver fern
#

I suppose I could construct the IEnumerator in the controller from the variables in the effect instead of returning the IEnumerator

grand snow
#

you dont construct it

edgy sinew
#

It just seems like, it should already be there

silver fern
#

well I have to give it the variables

grand snow
#

if you do IEnumerator e = StartBurnEffect() all you did is execute it once and its now yielded forever till called again

#

plz dont "return it" because that is just incorrect

silver fern
#

well I mean

grand snow
#

you can do Func<IEnumerator> e = StartBurnEffect; and pass around a func reference of it to start later.

silver fern
#

I thought that was obvious, mb. I was gonna use StartCoroutine(DealDamage()); to start it

edgy sinew
grand snow
#

I wanted to point this out but I am tired 😆

grand snow
edgy sinew
#

I’m just saying there’s so many paths to take avoiding creating new stuff at runtime 🔥

eternal needle
# edgy sinew I’m just saying there’s so many paths to take avoiding creating new stuff at run...

which is a pointless micro optimization unless you actually have issues with creating new stuff at runtime. At which point you should use the profiler to determine what the real issue is. A short lived effect, not even created nearly once per frame, isn't gonna do shit to your performance
the issues you had with new don't suddenly mean to avoid it for no reason. theres a time and place to avoid it in favor of stuff like pooling

#

you cant always avoid creating new stuff at runtime

mighty peak
#

Why i need regidbody?

#

Ant way yes its have a rigid

polar acorn
random lodge
#

Just to be curious is this one of those lines that is thought to be "best not to use often" or it's an easy "finder"? I know it's not an issue if you don't have a lot but I'm just practicing best methods as I can 😛 GameObject.FindGameObjectsWithTag("Dreadnought").Length

mighty peak
polar acorn
polar acorn
random lodge
#

I was thinking about just incrementing a variable each time a thing is spawned and decrement it any time I destroy it

#

but might not be entirely perfect (mostly because I am sure I'll forget where all those are to do it hah)

mighty peak
polar acorn
polar acorn
#

And remove them when they're destroyed

mighty peak
polar acorn
mighty peak
#

When i touch it its doesn't destroyed

random lodge
polar acorn
mighty peak
mighty peak
#

You can see it in code

polar acorn
mighty peak
polar acorn
silver fern
#

overlapping without moving doesnt trigger?

polar acorn
#

Well, you could explicitly call WakeUp on one, but until some force occurs on a rigidbody it won't be sending any messages

silver fern
#

interesting

mighty peak
#

Then its destroyed and happen what in code

polar acorn
#

I'm just going to repeat my question until you answer it

#

Which object is moving, and how are you doing the movement

mighty peak
#

Brroo

mighty peak
polar acorn
#

What code

mighty peak
#

You wll find in in /**/

#

This code

polar acorn
radiant voidBOT
polar acorn
#

Put it in a format that's actually readable

mighty peak
#

:/

#

Done

polar acorn
#
  1. Your movement is commented out. This means the object is not moving and therefore cannot have a collision.
  2. Your debug log is inside the if statement. Try logging the tag of the object you hit before the if statement to see if it's detecting any collisions at all
#

And in the future, use a bin if it's gonna be two pages of vertical text

mighty peak
polar acorn
#

So it's moving by gravity

mighty peak
#

Yes

polar acorn
#

When I said "how are you moving the object" you could have actually answered that

#

and said "gravity"

#

instead of pointing to code that is not doing the movement

#

and saved us both a lot of time

mighty peak
#

But ok

#

By mistake

#

Whats wrong now?

polar acorn
#

Now you put the log outside the if and see if it's detecting collisions at all

mighty peak
polar acorn
mighty peak
polar acorn
#

and log the tag of the object you hit

mighty peak
#

I made log to know if coins touched

polar acorn
#

because right now you only get a log if you hit something of a specific tag

mighty peak
#

so if I put it out how it will work

noble forum
#

Hi, any idea why it happens on a prefab?

polar acorn
#

Prefabs can exist anywhere. Scene objects only exist when that scene is loaded

#

You'll need to set the variables after spawning an instance of it

noble forum
polar acorn
mighty peak
real ferry
#

Use the CompareTag() function btw

mighty peak
#

and should work without if

polar acorn
#

so if it logs anything you'll know what thing you hit

#

and potentially why it wasn't working

silver fern
#

Debug.Log(other.gameObject.tag)

mighty peak
#

aaa

#

wait

polar acorn
#

Debug Log will print the thing you pass in. If you want to log a thing, you pass that to debug log

#

You know how to get the tag of the object you hit, you're already doing that

#

so, log it.

mighty peak
#

doesnt destroyed

real ferry
#

Looks Like the tag

teal viper
#

Also share !code properly

#

!code

radiant voidBOT
silver fern
teal viper
#

Gotta keep telling until they get it.

mighty peak
silver fern
mighty peak
silver fern
teal viper
mighty peak
polar acorn
# mighty peak ok

So it sounds like it's being detected just fine. If you didn't get the log before, then the object's tag is not "coin"

#

It could be "coin " or " coin" from the looks of things

mighty peak
#

but any way its should work if any thing tuch it like that

polar acorn
#

Using CompareTag would tell you if the tag you're trying to use doesn't exist

teal viper
mighty peak
polar acorn
# mighty peak

Again, that could very well be coin or coin instead of coin

silver fern
mighty peak
mighty peak
silver fern
#

youre destroying the wrong thing

mighty peak
mighty peak
silver fern
mighty peak
#

the love each

silver fern
#

put your mouse cursor into the text field where it says coin and delete empty space if there is any

mighty peak
#

like i didnt writed destroyed

#

where is space?

silver fern
#

not there, in unity

twin pivot
#
private void OnTriggerEnter(Collider2D collision)
{
  if(collision.gameObject.CompareTag("coin"))
    {
      Debug.Log("working")
    }
}
#

should be this, no?

silver fern
#

I don't remember where to see the tag manager

real ferry
#

If U add a new Tag iirc

twin pivot
#

click add tag

silver fern
#

looks like you can't actually check if there's an extra space at the end

twin pivot
#

you just have to delete and readd

mighty peak
#

how should i find space?

real ferry
#

Just do If collision.gameObject.tag.contains("coin") or smth 🤣

#

Temu fix

silver fern
polar acorn
real ferry
#

Ik

mighty peak
polar acorn
#

CompareTag is literally designed for this problem

#

it'll tell you if the tag you want doesn't exist

#

It'll give you a warning in the console

real ferry
twin pivot
mighty peak
#

anyway now is there any issues in code or try rewrite the tag?

polar acorn
silver fern
real ferry
real ferry
twin pivot
#

try this and see if u get the debug message

real ferry
#

Wdym same

silver fern
mighty peak
#

wait

real ferry
#

What

mighty peak
#

remote session end wait 🙂

real ferry
#

What remote session

#

What are we talking about

twin pivot
#

are we talking to a chatbot?

silver fern
#

no

mighty peak
#

im using remote desktop so

silver fern
#

I think google translate is just pretty bad at arabian languages

real ferry
#

Oh okay

real ferry
#

Maybe use deepl

#

Its better usally

#

Or maybe really ask ai for translation

mighty peak
mighty peak
real ferry
#

Okay

mighty peak
#

so make debug back in if?:/

real ferry
#

Wdym

teal viper
#

It's hard to understand sometimes. Other times it's ambiguous.

twin pivot
mighty peak
polar acorn
mighty peak
#

wait 🤷

polar acorn
#

So now try compare tag

mighty peak
mighty peak
polar acorn
mighty peak
#

here its

real ferry
#

There is No compareTag

#

U do ==

mighty peak
silver fern
#

if (other.gameObject.CompareTag("coin"))

mighty peak
#
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "coin")
        {
            Debug.Log("its work :/");
            scoreValue += 1;
            score.text = scoreValue.ToString();
            Destroy(gameObject);
        }
        //Debug.Log(other.gameObject.tag);
    }


#

oh ok

real ferry
#

Oh

mighty peak
#

aaaa

#

its be 1!!!

real ferry
#

Wdym 1

#

Oh

mighty peak
real ferry
#

Nice

mighty peak
#

and back to 0

#

and be1

real ferry
#

Good ig?

mighty peak
#

what let me understand what happening

#

how should i add onclick to icon ? 🙂

twin pivot
mighty peak
#

but let me try something

twin pivot
mighty peak
#

its work!

#

just change coin to player

#

but i gt thats

real ferry
#

Ye Cuz Ur trying to access Something thats gone

#

The Error is pretty clear tho

#

You should try to understand Error Messages but that comes with time i guess

mighty peak
real ferry
#

Double click the Error

mighty peak
#

i hate this blocked ny sever

mighty peak
#

and its open that

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

public class spawner : MonoBehaviour
{
    public GameObject[] spawns;
    float timeBtwSpawns = 1;
    
    void Start()
    {
        
    }

    
    void Update()
    {
        timeBtwSpawns -=Time.deltaTime;

        if (timeBtwSpawns <= 0)
        {
            timeBtwSpawns = Random.Range(0.5f, 1.5f);
            Vector2 spawnposition = new Vector2();
            spawnposition.x = Random.Range(-2.5f, 2.5f);
            spawnposition.y = -6;
            Instantiate(spawns[Random.Range(0, spawns.Length)], spawnposition, Quaternion.identity);
        }


        
    }
}
#

im really didnt say specific object

#

how i write this sht since 2 years

mighty peak
#

or something

ivory bobcat
mighty peak
mighty peak
#

now its destoyed but doesnt respawn

#

void Update()
    {
        timeBtwSpawns -=Time.deltaTime;

        if (timeBtwSpawns <= 0 && spawns.Length >= null )
        {
            timeBtwSpawns = Random.Range(0.5f, 2.5f);

            Vector2 spawnposition = new Vector2();
            spawnposition.x = Random.Range(-2.5f, 2.5f);
            spawnposition.y = -6;
            Instantiate(spawns[Random.Range(0, spawns.Length)], spawnposition, Quaternion.identity);
        }


    }
}```
dense goblet
#

Hey, Im very very new to Unity and C#, but Im kinda struggling a lot with refrencing game objects in scripts, for example, lets say I have a player, and I want them to enter a trigger box to teleport across a river, I wouldn't have the slightest idea how to refrence the trigger box.

#

also, please don't forget about G NOUR's problem*

slender nymph
#

you don't need to have a direct reference for that, you would use something line OnTriggerEnter which provides the reference to the other object

mighty peak
#

but can i get some help ? 🙂

slender nymph
#

pay attention to the warnings in your IDE

dense goblet
slender nymph
#

sure, if that is how you want to do it

mighty peak
slender nymph
mighty peak
#

oh thats for me

#

no i need help to know whats wrong in my code

#

i do that but

ivory bobcat
#

Are there any console errors?

ivory bobcat
slender nymph
mighty peak
#

i dont think thats what i want

#

i just need it if its less that 5 or null and if times ends respawn again bettwen 0.5 and 2.5 seconds

ivory bobcat
mighty peak
naive pawn
#

the issue is perhaps the 999+ errors you have

analog pendant
mighty peak
naive pawn
#

perhaps the one your ide is highlighting?

#

buddy there are tools here to help you

#

put some effort in

mighty peak
#

huh 🙂

mighty peak
#

so its wont be null

naive pawn
#

no

#

spawns.Length is an int

#

you probably need to go do c# basics, see pins

mighty peak
naive pawn
mighty peak
naive pawn
#

the entire window is the console

mighty peak
naive pawn
#

the detail area is part of the console

#

check the thing that's actually null instead of some random value

#

put some thought and effort into this

#

don't just stumble around randomly hoping itll work

mighty peak
#

when its up to 7 y destroy and after destroy if be null or > 1 spawns

mighty peak
random lodge
#

Alright, someone tell me how I screwed this up. The OverlapCircle line stops the spawns. The circle is pretty small, I checked. 😛

ivory bobcat
# mighty peak aaa its gave me same null errors also

Alright, I'll simply tell you it straight.
You've got a null reference exception because you've destroyed something that you're still referencing.
We need to know what object threw the error. Which line. Why was it destroyed. If it's a prefab or scene object. Etc.

mighty peak
slender nymph
random lodge
#

Yup did that

#

Wait I have an idea

#

Ok I might be a dork

slender nymph
#

then you should see what collider(s) the circle is over top of

random lodge
#

I had a collider on that spawner. SMH.

mighty peak
#

guys please reply me when the massage is for me 🙂

random lodge
#

Why is it that the obvious answer comes to you after you ask even when you've tried for hours to figure tha tout

#

lol

mighty peak
#

i dont know which one you talking about

mighty peak
#

im reached to close wall

random lodge
#

I'm a newb but my guess is check if it exists before you reference it

dense goblet
slender nymph
mighty peak
#

I think i send all of this

#

But delete coins maybe its effect

mighty peak
ivory bobcat
#

!code

polar acorn
radiant voidBOT
mighty peak
#

Oh

#

I think you say make new bot add entire code for normal code

mighty peak
#

Its for coins

#

And im talking about squares

teal viper
#

You should really use Google translate or something...

mighty peak
#

Without coin

#

I deleted it

mighty peak
#

No just can't read more🙂

#

Need a break 😂

teal viper
#

It's not just read. It's write too.

mighty peak
teal viper
#

We end up needing to guess what you mean half of the time...

ivory bobcat
#

You could've probably solved this 4 hours ago.
Stop doing random solutions.
Show us the object and script that calls Destroy.
It's your script with the TriggerEnter2D callback method.
Show us the details pane for the console error.
As is, I'm assuming you're referencing scene objects and cloning rather than referencing an asset-prefab

teal viper
#

This is not very inviting to help you

mighty peak
#

Trigger enter is for players touching coins ok?

#

Leave it

mighty peak
mighty peak
mighty peak
mighty peak
ivory bobcat
#

Alright. My last response since you're unable to understand the problem. You're referencing something that you've destroyed during runtime. You need to figure out what object has been destroyed. Not "leave it" alone because it isn't throwing any immediate errors.

#

Good luck.

mighty peak
mighty peak
#

And i deleted coins from respawns for that's

#

So that the player does not take it and another problem occurs now

mighty peak
mighty peak
ivory bobcat
#

You're wasting my time. Don't message me anymore please. Thank you.

polar acorn
slender nymph
#

!learn

radiant voidBOT
umbral hound
#

Can someone tell me what this does?

public static void Shuffle<T>(this IList<T> ts) {
        var count = ts.Count;
        var last = count - 1;
        for (var i = 0; i < last; ++i) {
            var r = UnityEngine.Random.Range(i, count);
            var tmp = ts[i];
            ts[i] = ts[r];
            ts[r] = tmp;
        }
    }
umbral hound
slender nymph
#

that explains the algorithm being used which should make it clearer what each line is doing (especially since each individual line is incredibly simple)

umbral hound
chilly elm
#

And I had it since I was born

ivory bobcat
#

Doesn't seem Unity specific though so you're probably better off asking the csharp discord server

radiant voidBOT
#
<:error:1413114584763596884> Command not found

There's no command called csds.

umbral hound
ivory bobcat
teal viper
chilly elm
#

Can anyone teach me unity?

quartz jasper
#

youtube

fickle plume
chilly elm
fickle plume
#

@chilly elm I think you do. As it has been made abundantly clear to you that there's no off-topic on the server. Consider this is a last warning.

chilly elm
#

!learn

radiant voidBOT
rapid wadi
#

me and my groupmates are working together for uni so im commiting a empty project so he can clone and also work on it, but the packages folder is like 200 mb

is the best way to go is just me sending him the project as a zip and then commiting only stuff we add in the assets folder like scripts sprites etc?

fickle plume
#

Make sure .gitignore file is configured properly

#

!vc

radiant voidBOT
# fickle plume !vc
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

rapid wadi
#

oh ok lol ill look at that thanks

limber turtle
#

i think i have a runtime error in my code but i don't know how to find it. i can't share my code bc i'm at school right now and discord is blocked on my laptop

#

can someone help, or am i being too vague?

#

i made a function that gives a coin access to a list of other coins to find the closest one and trigger a redirect function when shot

#

but shooting a coin freezes the editor and crashes unity

keen dew
#

You have an infinite loop. It's usually caused by having a while loop that doesn't end

limber turtle
#

i don't, it's a foreach loop

#

well i probably do

#

but it's not a while loop

keen dew
#

ok

limber turtle
#

wait i think i might have found it

#

but i'm not sure how to address it

#

i have the foreach loop to determine the closest other coin, if a ray can be cast without hitting a wall between the two coins then the same function is called on the other coin

#

it's recursive and ends when the list has no more coins that can be hit

#

so why is it breaking with only one coin active?

naive pawn
#

well is the list being changed?

#

consider flattening it out to have it not be recursive

limber turtle
#

each coin is removed from the list to avoid being compared with itself

#

i'll see if i can copy it into an email draft to post here

naive pawn
#

!code

radiant voidBOT
limber turtle
#
void RedirectCoin(GameObject otherProjectile)
    {
    
        SlingerCoinScript closestCoin = null;
        float closestDistance = 0f;
        slingerScript.activeCoins.Remove(gameObject);
        foreach (var coin in slingerScript.activeCoins)
        {
            SlingerCoinScript otherCoinScript = coin.GetComponentInChildren<SlingerCoinScript>();
            Vector2 coinVector = currentPosition - otherCoinScript.currentPosition;
            RaycastHit2D hit = Physics2D.Raycast(transform.position, coinVector, coinVector.magnitude, LayerMask.GetMask("Surface"));
            if (!hit)
            {
                if (closestCoin != null)
                {
                    if (coinVector.magnitude < closestDistance)
                    {
                        closestCoin = otherCoinScript;
                        closestDistance = coinVector.magnitude;
                    }
                }
                else
                {
                    closestCoin = otherCoinScript;
                    closestDistance = coinVector.magnitude;
                }
            }
        }
        
        if (closestCoin != null)
        {
            Debug.DrawRay(transform.position, closestCoin.currentPosition - currentPosition, Color.blue, 2f);
            closestCoin.RedirectCoin(otherProjectile);
        }
        else
        {
            Destroy(otherProjectile);
        }
        Destroy(gameObject);
             
    }
#

ik how to do it, i just can't post it from my laptop

#

if any clarification is needed on some parts please say

naive pawn
#

oh so it isn't recursive?

limber turtle
#

i thought it could be considered recursive

#

but no, i suppose

#

i don't know where my code would be looping infinitely

#

i'm using finite loops and it shouldn't be calling the same function in other coins when there are no other coins

naive pawn
#

i feel like it being "recursive" doesn't really solve anything

#

you could just have a nested loop in whatever slingerScript is

limber turtle
#

i might not be clarifying well enough

#

slingerScript is the script that contains the abilities of the gunslinger character i'm making

#

throwing a coin to shoot is one of his abilities

#

shooting a coin makes it look for the closest coin to bounce to and trigger another redirection

#

but when i shoot the coin, unity crashes

#

presumably a runtime error

naive pawn
#

typical runtime errors don't cause crashes

#

does it crash or freeze?

limber turtle
#

oh

#

it freezes for a bit and then crashes

naive pawn
#

check logs for more info then

#

!logs

radiant voidBOT
# naive pawn !logs
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

naive pawn
jolly stag
#

Hello all, I'm having some difficulty getting a weapon switch script to work, it should be tied to the scroll wheel and it was actually working yesterday but for some reason it's returning null due to the object reference not being set. I would apricate any help :)

using UnityEditor.Rendering.LookDev;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    InputAction scroll;
    Vector2 scrollPosition;
void Update()
{
        scrollPosition = scroll.ReadValue<Vector2>();
        if (scrollPosition != Vector2.down)
        {
            scrollNumber++;
        }
        if (scrollPosition != Vector2.up)
        {
            scrollNumber--;
        }
        if (scrollNumber == 10)
        {
            scrollNumber = 0;
        }
        if (scrollNumber == -1)
        {
            scrollNumber = 9;
        }
  }
}```
hexed terrace
#

The error will tell you which line has a NRE. Read that line, work out which object hasn't been set ... make sure it's set before trying to use it

#

Gonna assume it's scroll that hasn't been assigned

jolly stag
#

The line is scrollPosition = scroll.ReadValue<Vector2>();

hexed terrace
#

Yeah, scroll is null

jolly stag
#

Why is that? It should be reading the value from the input system no?

hexed terrace
#

because you haven't assigned anything to scroll

#

This
InputAction scroll;

Declares are variable called scroll of type InputAction ... it's an empty box until you tell it which instance of InputAction to use.

jolly stag
#

Urgh my discord is now playing up

wintry quarry
jolly stag
#

Right there we go I can talk again That makes sense, so how would I go about assigning something, I believe it should be something after InputAction scroll but I am stumped as to what

wintry quarry
#

Either make it public and set it up in the editor or you get the reference from an InputActionReference or InputActionsAsset

hexed terrace
#

= is for assignment.

jolly stag
wintry quarry
#

The only way it would have worked is if they were serialized/public or you assigned them

jolly stag
wintry quarry
#

What you're describing doesn't make sense, you can't just declare a random variable and it magically knows what bindings and action type etc you want

#

If you're confused you need to go back to your other ones and look what you did because it certainly wasn't this

jolly stag
#

Agreed, I think I've just found the issue. Let me test and get back to you

rough sluice
#

Ok

jolly stag
#

Alright, this is what I've just tried and I'm still getting the same error ```using JetBrains.Annotations;
using UnityEditor.Rendering.LookDev;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
InputAction scroll;
Vector2 scrollPosition;
public int scrollNumber = 0;
void Start()
{
scroll = InputSystem.actions.FindAction("Weapon Switch");
}
void Update()
{
scrollPosition = scroll.ReadValue<Vector2>();
if (scrollPosition != Vector2.down)
{
scrollNumber++;
}
if (scrollPosition != Vector2.up)
{
scrollNumber--;
}
if (scrollNumber == 10)
{
scrollNumber = 0;
}
if (scrollNumber == -1)
{
scrollNumber = 9;
}
} ```

hexed terrace
#

if scroll is still null.. then your assignment in Start() is failing to find the action

jolly stag
#

I feel like I'm going insane, this is the InputManager that I have set up. As far as I can tell the action that I've listed for the scirpt to find is correct.

midnight plover
#

If you do not have any other script handling your input system, you need to create a reference to it on start before using it.

#
inputActions = new WhatEverYourInputActionsetIsCalled();
inputActions.Enable();
jolly stag
#

Reading now :)

limber turtle
#

could i make a raycast call OnTriggerEnter2D? if so then that could stop me from having to use a recursive function

#

i thought it would be controlled but apparently not, i commented it and my game stopped crashing

midnight plover
#

I am having a hard time getting what you mean exactly.

limber turtle
#

hold on

#

it'll take me a while to share a video or picture bc i'm on school wifi

#

basically, you know how ultrakill's coins work?

#

i have a list of coins that the player can shoot, shooting one coin causes it to look for the next coin and makes that coin look for the next

#

i've done this with a recursive (?) function but it freezes and crashes unity

#

idk what's going wrong with it

keen dew
limber turtle
#

oh

#

is there a way i could fix that, or will i have to redo it?

keen dew
#

Use a debugger to step through the code and see what it actually does

#

If that's the reason then slingerScript.activeCoins.Remove(GetComponentInChildren<SlingerCoinScript>().gameObject) probably fixes it. But that's just a quick crutch to verify if that's it

#

If the only use for the activeCoins list is this method, change it so that it stores these objects directly instead of objects that have the SlingerCoinScript component

civic smelt
#

germans here ?

fickle plume
civic smelt
#

ahh okay thank u

grand snow
#

im sure many germans speak english!

silver fern
#

I'm guessing he doesn't

brave idol
#

Hi, I'm making a farming game for a college project and I'm currently having an issue where because my FarmManager gameObject is dontDestroyOnLoad it's being carried across scenes but it has properties that are tilemaps on a certain scene. When I switch scenes the farmManager is being carried across scenes because its dontDestroyOnLoad but the tilemaps arent. I've tried making my grid object, which is the root object for my tilemaps, DontDestroyOnLoad but when I do that it gets duplicated and breaks my game. Ive tried using a singleton pattern to fix this but it doesnt seem to work. any advice? thanks

Below is the PersistentObject script that I'm using to make the grid DontDestroyOnLoad


public class PersistentObject : MonoBehaviour
{
    private void Awake()
    {
        GameObject rootObject = gameObject;

        if (rootObject != null)
        {
            rootObject = gameObject;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}
grand snow
wintry quarry
#

But yes your Singleton implementation is definitely wrong

brave idol
brave idol
hollow zenith
#
ObjA.Awake
ObjA.OnEnable

ObjB.Awake
ObjB.OnEnable

Is this correct order of execution? OnEnable runs immediately after Awake for each object, meaning I have to do something like:

void Start()
{
    Player.Instance.OnDamageTaken += UpdateHealthBar;
}

void OnEnable()
{
  if(Player.Instance != null)
  {
      Player.Instance.OnDamageTaken -= UpdateHealthBar;
      Player.Instance.OnDamageTaken += UpdateHealthBar;
  }
}

void OnDisable()
{
    Player.Instance.OnDamagaTaen -= UpdateHealthBar;
}

This way I am guaranteed to subscribe to Player object event?

#

Start works because Player Instance will not be null since its set in Awake, but I cant use OnEnable as it will only work if Player happens to instantiate before my other object.

rich adder
hollow zenith
#

But I have to do OnDisable UnSub, hence the above

#

Afaik subscribed event will throw an error if the object is disabled?

hexed terrace
#

Sub in OnEnable, unsub in OnDisable - if you're toggling the active state

hollow zenith
#

OnDisable is guaranteed to run even if the object is destroyed right? It runs even when I exit the playmode

hollow zenith
#

Yeah but to guarantee it(without using script execution order) I have to do extra step in Start() to sub

hexed terrace
#

that's one way, not the only way

rich adder
#

idk I find it easier to just have the singletons have a slightly early execution order

hollow zenith
#

I could start with object disabled too hmm

#

So you set singletons in script execution order?

rich adder
#

I just change them so they run earlier so they are ready for other scripts OnEnable

#

is considered bad practice / iffy design but it depends

hollow zenith
#

I might give it a go tbh, it does sound like a good idea
I just need to make sure not to write too much spaghetti

grand snow
#

why do people keep wanting to sub and unsub to events with enable/disable

hexed terrace
#

It's best to try and avoid changing the script execution order

hollow zenith
#

To make sure you dont have any leftovers

grand snow
#

but i keep seeing people sub on awake/start but unsub on disable

hexed terrace
hollow zenith
#

That is wrong imo, you need to cover all cases I think(awake/start + onDisable)

grand snow
#

If it was me id just have my subscription check enable state instead of unsubscribing

rich adder
#

if you disable and enable object then yes Start/Disable makes no sense cause if you re-enable you have no sub anymore

wintry quarry
#

Why does FarmManager need references to tilemaps anyway though

hollow zenith
#
        private void Start()
        {
            PartyController.Instance.OnMovementSpeedChange += UpdateMovementSpeedText;
        }

        private void OnEnable()
        {
            if (PartyController.Instance != null)
            {
                PartyController.Instance.OnMovementSpeedChange -= UpdateMovementSpeedText;
                PartyController.Instance.OnMovementSpeedChange += UpdateMovementSpeedText;
            }
        }

        private void OnDisable()
        {
            PartyController.Instance.OnMovementSpeedChange -= UpdateMovementSpeedText;
        }

Would you consider this a good practice in general?
Ignoring the purpose of small text change which could be changed to update more things(or even done in Update)

#

Are there better solutions for updating UI? We've had similar talk before and I thought that using events makes sense to keep UI and logic separate.

#

This is just 1 text to update, but there will be much more(either 1 event per text field or general block of data or 1 event for all relevant UI like player stats)

#

For example I could update whole inventory this way or only 1 inventory cell(as an item is moved/added/removed from specific cell)

rich adder
hollow zenith
#

In this example the above class would never be a singleton as it's purpose is to subscribe to what it requires right?

What about naming? The above class is called something like "WorldUIController", but it's not a singleton while PlayerController is a singleton.

I might have messed up the names a bit 😄

#

Should I just call it WorldUI? Since it's not sending anything outwards, just receiving events.

rich adder
hollow zenith
#

What would you say the difference is between managers and controllers? Would both be monobehaviors?

hollow zenith
#

Is there something I can read up on standard namings for such things?

rich adder
#

Controller generally, when it controls something specific. Like ChracterController Animation Controller etc..
Manager is when it takes care of multiple systems , Game Manager, UI Manager etc.

hollow zenith
#

Controlls something directly?

#

makes sense

#

Directly as in with a direct calls, not events

rich adder
#

its just naming for sake of own organization , there isn't like a set book or anything

hollow zenith
#

There should be something tho

rich adder
#

they got c# naming conventions , and I think unity has some general gaming jargon ebook

hollow zenith
#

Organizing code is pretty big topic imo

rich adder
#

yes which is why its usually done to whatever standards you setup, as long as they are consistent

hollow zenith
#

I did some research and I am doing better than before.
The best change I made is to organize scripts by their purpose instead of type(or however it's called)

rich adder
#

like people normally name a singleton Instance
i've seen places (even in unity) where they name Singleton instead

hollow zenith
#

Meaning all player scripts go into Player folder(including UI related to the player as well as scriptable objects and assets/sprites)

dense goblet
#

I have a very basic question, Im trying to make a scrip that resets the position of the player when a BoxCollider2D meshes with another BoxCollider2D. but, despite making the collider box a trigger, and coding it with both OnColliderTrigger2D and OnTriggerEnter nether are giving me results


public class FallScript : MonoBehaviour
{
    public GameObject Player;
    // 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()
    {
        
    }
    void OnCollisionEnter2D()
    {
        print("worked2");
        Player.transform.position = new Vector2(0f, 0f);
    }
}
#

*wrong script sorry

hollow zenith
hollow zenith
hexed terrace
#

!vs

radiant voidBOT
# hexed terrace !vs
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

rich adder
dense goblet
hollow zenith
#

I know, but I thought that some languages have Singleton keyword similar to C# having class

#

maybe not hmm

rich adder
rich adder
hollow zenith
#

oh yeah Unity.huh is quite good, I need to use it more often myself instead of relying on chatgpt(which I feel got really stupid, even tho I am not using it that much)

rich adder
#

ofc its only gonna get stupider with the more bad recycled code it learns on

hollow zenith
#

true

dense goblet
#

Worked, tysm

silver fern
#

to keep a link between an effect Object and an associated timer coroutine, would it be best to keep them in a dictionary or a list of lists or arrays or similar?

rich adder
#

uhh wasnt this solved/ discussed already a while ago?

silver fern
#

no I'm redoing the whole system

rich adder
#

wasnt the overall thing to just keep the Coroutine stored on the effect that wants it run ?

silver fern
#

yes but I'm no longer doing that because the effects are not monobehaviors

rich adder
#

yes but you can Start Coroutines on ANY mb

silver fern
rich adder
#

you can keep the actual IEnumerator method in pocos too as long as StartCoroutine is done on a MB

rich adder
#

assuming effects controller is MB ofc

silver fern
#

yeah it is

#

let me see

hollow verge
#

hey i plan to have my html game build differently depending on the user's platform
if i understand right preprocessor directives, #if and #endif's are the way to do it?

rich adder
#

also if needed you can store coroutine / StartCoroutine in a Coroutine variable

silver fern
#

where mono was the MB I passed in

rich adder
hollow verge
# rich adder yea

thx then i have a problem
i'm missing script symbols and i can't find a solution online
could you pretty please cherry on top help me

silver fern
#

is coroutine just the IEnumerator then?

rich adder
rich adder
#

coroutines are not a unity concept

hollow verge
rich adder
#

they are using the IEnumerator interface to do it

silver fern
#

I mean I return the IEnumerator to store the coroutine without starting it immediately

rich adder
rich adder
hollow verge
rich adder
hollow verge
rich adder
hollow verge
slow blaze
#

anyone know what this error is? I can't find anything on it

rich adder
rich adder
slender nymph
hollow verge
slender nymph
#

then it's likely an issue with your setup which is specific to that asset. we don't support third party assets here

dense goblet
#

Idk if this is a direct programming question, but when I move my camera with a script, it goes blank?


public class Camera_Move : MonoBehaviour
{
    public GameObject Player;
    public GameObject Camera;
    // 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()
    {
        
    }
    void OnTriggerEnter2D(Collider2D collider)
    {
        print("Camera Move Script");
        Camera.transform.position = new Vector2(18f, 0f);
    }
}
rich adder
hexed terrace
hollow verge
slender nymph
sour fulcrum
dense goblet
rich adder
slender nymph
dense goblet
#

tysm

#

that worked lol

rich adder
#

if you ever need to change it can be done via inspector easily, instead of always changing and compiling the code every time

hollow verge
grand snow
#

they meant in unity editor project window

hollow verge
#

my bad

rich adder
dense goblet
rich adder
#

variables should def be one of the most important basics

hexed terrace
#

asmdef is a type, not a file name.. search won't find it by name like that

peak siren
#

would anyone have any clue why visual studio our of no where adding random spacing between lines for no reason. It is not a true space but a gap because i cannot put my cursor between in

rich adder
#

ya you would need t:asmdef

silver fern
rich adder
hollow verge
#

oh alr

peak siren
#

how do i get rid of that?

rich adder
hollow verge
rich adder
# hollow verge

yeah well there goes asmdef being culprit lol
not suure tbh.. did you try regen project files in unity?

grand snow
#

unity assets dont show in visual studio

#

and im not sure if that search is correct, wouldnt it be t:AssemblyDefinition ?

#

you can also search with explorer for *.asmdef

rich adder
#

it works but i guess there are none in assets folder

#

their Conditional compilations arent showing

#

but apparently VS is configured properly so. 🤷‍♂️

#

something obvious I'm probably overlooking?

grand snow
#

I dont even know what the original issue is

#

a thread would help 😉

peak siren
#

Thanks that fixed it.

I do have another strange issue.

When ever I hit play on any game project, it would have this strange pause before fully playing. Example a character moving. It would be a delay before i can move the character then it will let me move it.

This only happens within the engine. When I build and play as stand alone this does not happen. This happens with every project 3D or 2D. I found that changing "when entering play mode" settings "do not reload Domain or scene" stops this from happening but before unity 6, i never seen this behavior before

grand snow
#

what does "play on any gameobject" mean

#

you play a scene, if a gameobject is selected or not doesnt mean much

dense goblet
#

How do I call Public Variables in other scripts?

slender nymph
polar acorn
jolly stag
# jolly stag Reading now :)

In case anyone else somehow finds this and has the same issue, the jump in input manager was set to axis and not vector2. Thank you Carwash, PraetorBlue and joer for helping me

dense goblet
#

tyty\

analog pendant
#

how to clamp the rotation of X axis of camera

shell sorrel
#

can adjust it with euler angles and simple use Mathf.Clamp on the x axis

analog pendant
#

transform.eulerAngles = new Vector3(Mathf.Clamp(transform.eulerAngles.x-XRotation, -60f, 60f), transform.eulerAngles.y+YRotation, 0);

shell sorrel
#

likly due to the retruned angle from it being in the 0 to 360 range

#

you might want to do something like

Vector3 eulerAngles = transform.localEulerAngles;

if(eulerAngles.x > 180f)
    eulerAngles.x -= 360f;```
to bring it into the -180 to 180 range
#

before doing the clamp

analog pendant
shell sorrel
#

you are trying to clamp between -60 and 60, issue is the numbers returned by localEulerAngles are never negative

#

so the code above converts that 0 to 360 range to a -180 to 180 range that you can clamp

analog pendant
#

helped

#

but thanks I understood alot

#

that will help me find the solution myself

keen dew
#

Modifying Euler angles this way doesn't usually work very well. Make a separate variable (private Vector3 camRotation;), change that variable instead, and set the camera rotation based on it (transform.eulerAngles = camRotation;)

silver fern
#

how do I go about listening to an event from an unrelated instantiated object?

grand snow
#

what does that even mean

#

get the object instance and sub to its event?

#

Normal OO concepts apply with events, they are either a member field/property or are static

silver fern
#

I don't really have a good way of getting that instance

#

I guess I have to do it some other way

sour fulcrum
#

If you want to listen to that event it sounds pretty related

grand snow
#

then whatever you need from the instance can be done (including subscribing to its event)

silver fern
#

but then I have to check every update if the object exists

grand snow
#

then step back and perhaps we can figure out how to do this better

#

usually if you say want to subscribe to an event on a newly spawned thing, whatever does the spawning will subscribe OR have an event that other things can sub to so they can react to newly spawned instances.

silver fern
#

yeah I could do that

#

is there a good way to check if an object has an event?

grand snow
#

Well if you made the component and you know what the events are then you will handle these specifically

#

E.g. my enemy spawner spawns enemies and I sub to the enemies OnDie event

silver fern
#

yeah one of my effect objects is supposed to invoke the event, I could subscribe to it in the effect controller and forward it that way, but not all effect objects have an event so I should check if the object has an event before I can subscribe to it

grand snow
#

If different effects have different events then you either handle each specially or correct the design

silver fern
#

yeah but to handle them specially I have to check if the event exists

grand snow
#

Otherwise inheritance is used correctly so the common base has the events required

#

That doesn't work

#

If we want to handle all effects then they all need common events and functions

silver fern
#

thats not possible, I need a different solution then

grand snow
#

You do or a better design

#

Look at Component for example, a game object doesn't need to know what types they really are, it just knows it has components with common functions like Start()

polar acorn
#

If you ask ten people you're going to get ten different designs. You need to actually sit down and chart out every single effect you are going to need and start trying to group them. Find out when things happen, which outside things it needs to know about, what could trigger these things, what kind of things these affect, and so on

silver fern
#

yeah I know that but this is a special event from a certain effect, not something the effects have in common

polar acorn
#

Every time you ask this a different person is going to give you a different way to design this but the simple fact of it is you need to actually plan it all out.

#

You need to quantify everything you're going to need up front and find out how few of them you can use

#

make a hierarchy of which things are sub-groups of which things, and build out a structure

#

This isn't really a code problem. It's a design problem.

#

Without the design first, you can code a solution that gets like 80% of the way there

#

but you won't be able to find a fully realizable solution without knowing the full picture of what you need

silver fern
#

I already did that but there are edge cases

polar acorn
#

Then you make events for those edge cases

silver fern
#

yeah thats what I'm trying to do

polar acorn
#

If you have one effect that needs to be notified when a player lands on a platform, you make an OnPlatformLand event and give it to all of them

#

90% of the effects just go "Wow. This is worthless." and go about their day

#

but if you need it to happen, you make that event

silver fern
#

yeah that would work

#

wait no it wouldn't

grand snow
#

can you describe this special case?

silver fern
#

oh actually it might work

west sonnet
#

When I put references to a Singleton GameManager script in Awake, I get a nullreferenceexception error but when I put it in Start(), it works fine. Anyone know why that would be?

polar acorn
west sonnet
polar acorn
west sonnet
#

Is it because the Awake() is running before the GlobalReferences is initialized?

hollow verge
#

it is

slender nymph
# west sonnet When I put references to a Singleton GameManager script in Awake, I get a nullre...

if your singleton is set up in Awake then it is not guaranteed that one object's Awake method is run before another's. So what is happening is that object you are referencing the singleton in Awake is running its Awake method before the singleton's Awake method is run so the singleton has not been set up yet.
It is best practice to not access other objects until Start and to only set up an object's own state in Awake

silver fern
# grand snow can you describe this special case?

I have one effect that changes which kind of bullet the character can shoot, my current idea is to have a class like this

public class CounterShockEffect : Effect
{
    public event Action OnCounterShockOn;
    public event Action OnCounterShockOff;
    public override void ApplyEffect()
    {
        OnCounterShockOn.Invoke();
    }
    public override void UndoEffect()
    {
        OnCounterShockOff.Invoke();
    }
}``` and then have the effect controller call ApplyEffect() on it to invoke the event. The effect controller would listen to this event and invoke its own event that is listened to by the weapon controller where all the bullet related stuff takes place
west sonnet
#

Thanks!

grand snow
#

sounds like a shoddy design

#

Ideally an effect can be added to a player and removed in the same way and the effect itself is able to set itself up

#

e.g. player has functions or things that allow modification of the bullet shot and the effect itself can replace or change this itself

#

rn it seems like you have this Effect abstraction but are not using it well

rich adder
silver fern
#

how would they be null

rich adder
polar acorn
#

If an event has no listeners, it's null

silver fern
#

ah ok

polar acorn
hollow verge
#

since i'm missing platform symbols for preprocessor directives - if i add, for example, UNITY_IOS here, would it work regularly

grand snow
#

but why

#

they arent missing

#

its not defined if you are not CURRENTLY on the ios platform in the project

#

e.g. swap to ios, UNITY_ANDROID is no longer defined

hollow verge
#

oh my god is that so

rich adder
#

true

grand snow
#

I think in editor they exist if you have the platform installed however

#

but in builds the relevent platform defines exist for that plat only

#

I forget tbh

quartz jasper
#

can anyone recommend me good unity asset to create car (free)

polar acorn
hollow verge
#

so wait can i actually write UNITY_IOS even if it's undefined and it'll build for ios platforms

hollow verge
#

Oh My God

slender nymph
grand snow
#

the point of these is to have certain parts of a .cs file be included in compilation for certain platforms only

#

e.g.

#if DEBUG
Debug.Log("cool debugging shit");
#endif
hollow verge
#

just deadass thought i was missing a way to check if the platform was IOS

grand snow
#

there is Application.platform as a runtime alt

rich adder
#

who knew unity only shows them when you switched build profile / module

grand snow
#

its not shows but they are not defined when not needed so your ide doesnt show them

hollow verge
#

i know i just really didn't want to add to the runtime without needing to

grand snow
#

so yea you can use UNITY_IOS just fine happy days

red igloo
hexed terrace
red igloo
#

nevermind I fixed it! had the gravity as !isgrounded

limber turtle
#

alright, so i've fixed my issue with shooting coins causing infinite recursion and that part's working mostly fine now. my current issue is that because i have two colliders, one larger one to act as the hitbox for projectiles to bounce and a smaller one on the parent object for the coin's physics, the coin is now being destroyed when the larger collider touches the ground; sometimes i can't even throw it without it being immediately destroyed. is there a way to prevent this? i'm a little confused

#

if anyone needs elaboration i'm happy to oblige

umbral hound
#

What am I doing wrong here? I can't move and my active gravity goes down despite character being grounded

 private void GetMovement(Transform transform)
 {
     Vector3 vector = transform.forward * MovementInput.y + transform.right * MovementInput.x;
     m_MovementDirection.x = vector.x;
     m_MovementDirection.z = vector.z;
     if (MovementDirection.x > 1f)
         m_MovementDirection.x = 1f;
     if (MovementDirection.x < -1f)
         m_MovementDirection.x = -1f;
     if (MovementDirection.z > 1f)
         m_MovementDirection.z = 1f;
     if (MovementDirection.z < -1f)
         m_MovementDirection.z = -1f;
     if (m_CharacterController.isGrounded && m_ActiveGravity <= 0f)
     {
         m_ActiveGravity = 0f;
         m_MovementDirection.y = -0.27f;
     }
     else
     {
         m_ActiveGravity -= m_Gravity;
         m_MovementDirection.y = m_ActiveGravity;
     }
     m_MovementDirection = m_MovementDirection.normalized * CurrentSpeed;
     CollisionFlags collisionFlags = m_CharacterController.Move(MovementDirection);
 }
#

oh nvm I know the issues

slender nymph
#

just FYI, that chain of if statements comparing the X and Z axes against 1,-1 is definitely not how you clamp your input. just use Vector3.Clamp01 or normalize it if you don't need to support speeds less than 1. what you are doing is still going to end up with diagonal movement that is faster than forward/back and strafing

slender nymph
#

oh wait, I was misremembering the Vector3 method to use, I got it mixed up with Mathf.Clamp01, for a Vector3 you would use ClampMagnitude

umbral hound
#

Also there is no Vector3.Clamp01, only ClampMagnitude

#

Yeah

#

so for the max length I would just do 1f

#

what about for the negative clamp?

slender nymph
#

it's clamping the magnitude, magnitude is never negative

umbral hound
#

oh okay

#

thanks

umbral hound
#

It feels more like sliding than walking

slender nymph
#

show how you are actually applying movement

umbral hound
#

okay

#
private void GetMovement(Transform transform)
{
    Vector3 vector = transform.forward * MovementInput.y + transform.right * MovementInput.x;
    m_MovementDirection.x = vector.x;
    m_MovementDirection.z = vector.z;
    Vector3.ClampMagnitude(m_MovementDirection, 1f);
    if (m_CharacterController.isGrounded && m_ActiveGravity <= 0f)
    {
        m_ActiveGravity = 0f;
        m_MovementDirection.y = -0.27f;
    }
    else
    {
        m_ActiveGravity -= m_Gravity;
        m_MovementDirection.y = m_ActiveGravity;
    }
    m_MovementDirection = m_MovementDirection.normalized * CurrentSpeed;
    CollisionFlags collisionFlags = m_CharacterController.Move(MovementDirection);
    if (collisionFlags == CollisionFlags.Above && m_ActiveGravity > 0f)
        collisionFlags = m_CharacterController.Move(Vector3.up * -0.01f);
}
slender nymph
#

ah wait, it's at the bottom with the cc.Move call. so then it's likely how you are getting input

#

you're also normalizing after applying gravity which is wrong. and you don't need both the normalize and the clamp magnitude

#

your ClampMagnitude is doing nothing anyway since it returns the clamped vector

lofty mirage
#
protected override void Awake()
    {
        base.Awake();
        Debug.Log("Call FlyingEnemy.Awake()");
        bushesCollider = GameObject.Find("BushesTilemap")
                                   .GetComponent<TilemapCollider2D>();
        Debug.Log("bushesCollider: " + bushesCollider);
        flyingEnemyCollider = GetComponent<PolygonCollider2D>();
        Physics2D.IgnoreCollision(bushesCollider, flyingEnemyCollider, true);
    }

I want the dragonfries (which inherit this Awake() call; yes I checked, it is being called) to go through the bushes and all the bushes are on the BushesTilemap.

Do you guys have an idea why this is not allowing the dragonfries to go through the bushes? (dragonfries have PolygonCollider2D and BushesTilemap has a TilemapCollider2D)

umbral hound
slender nymph
umbral hound
#

oh wait, before gravity

slender nymph
#

that other info was just stuff that was wrong, not what was causing the sliding

lofty mirage
#

The alternative (easy) would be to create a flying enemy layer so that I would uncheck the collisions between flyingEnemies and bushes

umbral hound
#

Okay I was confused

slender nymph
#

this is still not showing the source of the input

umbral hound
#

yes it is

#

wtf

#

this is literally how I get input

slender nymph
#

note that the source of your input is in those MoveXRaw and MoveYRaw methods, not here, this is just where you are calling those methods

#

you also seem to be normalizing your input here, so why are you doing so again in the other method that uses the input to move the CC?

lofty mirage
red igloo
#

should I make separate variables and just do if the rb.velocity > 0.01f?

slender nymph
#

can you either have the courtesy of selecting the correct language so there's syntax highlighting when using pastebin, or use one of the recommended code sites from #🌱┃start-here (also in the bot command)

slender nymph
#

!code

radiant voidBOT
umbral hound
#

bro you can see it

slender nymph
#

it's literally cropped

umbral hound
#
public static class PlayerInput
{
    public static float MoveX() => GetInput(GamepadControl.GetAxis(InputControlType.LeftStickX), Input.GetAxis("Horizontal"));
    public static float MoveY() => GetInput(GamepadControl.GetAxis(InputControlType.LeftStickY), Input.GetAxis("Vertical"));
    public static float MoveXRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.LeftStickX), Input.GetAxisRaw("Horizontal"));
    public static float MoveYRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.LeftStickY), Input.GetAxisRaw("Vertical"));
    public static float LookX() => GetInput(GamepadControl.GetAxis(InputControlType.RightStickX), Input.GetAxis("Mouse X"));
    public static float LookY() => GetInput(GamepadControl.GetAxis(InputControlType.RightStickY), Input.GetAxis("Mouse Y"));
    public static float LookXRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.RightStickX), Input.GetAxisRaw("Mouse X"));
    public static float LookYRaw() => GetInput(GamepadControl.GetAxisRaw(InputControlType.RightStickY), Input.GetAxisRaw("Mouse Y"));
    public static bool Run() => GetInput(GamepadControl.GetButton(InputControlType.LeftStickButton), Input.GetKey(KeyCode.LeftShift));
    public static bool Jump() => GetInput(GamepadControl.GetButtonDown(InputControlType.Action1), Input.GetKeyDown(KeyCode.Space));
    public static bool Crouch() => GetInput(GamepadControl.GetButton(InputControlType.RightStickButton), Input.GetKey(KeyCode.LeftControl));
    public static bool Interact() => GetInput(GamepadControl.GetButtonDown(InputControlType.Action3), Input.GetKeyDown(KeyCode.E));
    public static bool Attack() => GetInput(GamepadControl.GetButtonDown(InputControlType.Action2), Input.GetMouseButtonDown(0));
    public static bool Pause() => GetInput(GamepadControl.GetButtonDown(InputControlType.Pause), Input.GetKeyDown(KeyCode.Escape));
}
#
private static T GetInput<T>(T inputGamepad, T inputKeyboard)
{
    if (!inputGamepad.Equals(default(T)))
        return inputGamepad;
    if (!inputKeyboard.Equals(default(T)))
        return inputKeyboard;
    return default(T);
}
lofty mirage
slender nymph
#

that was not directed to you, it was directed at the person who used pastebin. but you can see code sharing guidelines here: #💻┃code-beginner message

polar dust
lofty mirage
#

oh like

protected override void Awake()
    {
        base.Awake();
        Debug.Log("Call FlyingEnemy.Awake()");
        bushesCollider = GameObject.Find("BushesTilemap")
                                   .GetComponent<TilemapCollider2D>();
        Debug.Log("bushesCollider: " + bushesCollider);
        flyingEnemyCollider = GetComponent<PolygonCollider2D>();
        Debug.Log("flyingEnemyCollider: " + flyingEnemyCollider);
        Physics2D.IgnoreCollision(bushesCollider, flyingEnemyCollider, true);
    }
#

That's nice

#

i didn't know about cs after the backticks

polar dust
#

quick tip for strings, you can write the them as

// this
Debug.Log("bushesCollider: " + bushesCollider);
// is the same as this
Debug.Log($"bushesCollider: {bushesCollider}");```
lofty mirage
#

Oh actually I solved my pb, I had to ignore the CompositeCollider2D, not the TilemapCollider2D

dense goblet
#

Im kind of confused, I used to be able to see GameObject stuff in the inspector, but now its just simply not showing anymore?

keen dew
#

If you mean the Camera_Move script at the bottom, remove it and (try to) add it again

dense goblet
#

wait, it was because I had a compliation error

#

sorry

#

I guess while Im here, the editor is saying it doesn't recongize "Room" even though I establish it above?


public class FallScript : MonoBehaviour
{
    public GameObject Player;
    public GameObject Camera;
    public GameObject CameraTrigger;
    
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        GameObject Room = CameraTrigger.GetComponent<GameObject>();
    }
    void OnTriggerEnter2D(Collider2D collider)
    {
        print("worked2");
        Player.transform.position = new Vector2(0f, 0f);
        Camera.transform.position = new Vector3(0f, 0f, -10f);
        Room = 1;

    }
}```
#

Room Established in the first place

using UnityEngine;

public class Camera_Move : MonoBehaviour
{
    public GameObject Player;
    public GameObject Camera;
    public float Room = 1;
    void OnTriggerEnter2D(Collider2D collider)
    {
        switch (Room)
        {
            case 1:
             Camera.transform.position = new Vector3(18f, 0f, -10f);
             Room = 2;
                break;
            case 2:
             Camera.transform.position = new Vector3(0f, 0f, -10f);
             Room = 1;
                break;
                    
         }
    }
}```
polar acorn
#

Local variables cease to exist when the function they're declared in ends

dense goblet
#

tysm

wintry quarry
naive pawn
#

also, GameObject is not a component

#

what is even going on there

wintry quarry
#

(don't get confused with your other script which is completely irrelevant.)

dense goblet
naive pawn
#

ok, but GameObject isn't a Component, so it just doesn't make sense at all there

dense goblet
#

I seen it in Properties of the Component page

naive pawn
#

also, minor note (deal with this later) - you usually won't need serialized variables of type GameObject. use the type that you're actually working on, like Transform for Camera/Player, or... whatever you're trying to get from CameraTrigger

naive pawn
#

a component extends Component, not that it's inside Component

dense goblet
#

I guess so

naive pawn
#

colliders have a rigidbody property, but rigidbodies aren't colliders either

dense goblet
#

is there a list of Compoents out there to find one that would help me here?

naive pawn
#

you need to step back from the code and figure out what it is exactly that you're trying to do

dense goblet
#

Im trying to call on "Room" from the other script, to set it back to 1 when the Trigger event is done

naive pawn
#

you get a component you already know. if you were adding a component, that's when you'd be looking for existing ones

when you're at GetComponent, a list of available components in the engine isn't going to help

naive pawn
naive pawn
dense goblet
naive pawn
#

then you would use that type

polar acorn
naive pawn
#

make sure not to confuse the type vs the name of a variable

dense goblet
#

so would it be this? GameObject Room = CameraTrigger.GetComponent<CameraTrigger>();

polar acorn
#

You cannot store a value of type CameraTrigger in a variable of type GameObject

limber turtle
naive pawn
#

sounds like you're really confusing "is" vs "has" relations here (indicated by the "components have gameobjects" thing before)

dense goblet
#

honestly the entire line of code is stumping me

naive pawn
#

i mean, you don't need it to begin with

#

you can just have the variable named CameraTrigger be typed as a CameraTrigger

polar acorn
#

Green is a GameObject.

Red are components.

dense goblet
naive pawn
#

definitely not

polar acorn
naive pawn
#

ok, stop what you're doing

#

you're just stumbling randomly now

#

that won't be productive

#

go actually learn the relevant concepts here

#

have you done the unity essentials pathway?

polar acorn
#

GetComponent does exactly what it says it does. It gets a component. You tell it which kind of component you want to get.

#

Then you can put that in a variable

#

that can hold that kind of component

dense goblet
naive pawn
#

elaborate

dense goblet
#

I looked at the documentation, thats why Im here, because I looked at the documentation and tried to figure out but now Im here. I didn't thoroughly look through the huh how page, but it was confusing me so I looked at the documentation

also one moment on the elaboration*

polar acorn
dense goblet
# naive pawn elaborate

when I did the in engine essentials pathway (I scimmed most of what I already understood) when I got to the part with scripting, (I got several errors about the prewritten code that made the player character fly. the tutorial not telling me to make the player a rigidbody, and what type of rigidbody as well)