#archived-code-general

1 messages ยท Page 195 of 1

shell scarab
#

i also said "for example"

spring creek
#

"if Vector2s are not serializable to a file" I don't see you say "when they're not marked as serializable"
That is where the confusion came from. For me at least

shell scarab
#

i didn't know that it's YAML

quartz folio
#

What case are you talking about when you say they're not serializable, there are thousands of serializers

cosmic rain
#

Maybe share the code that you use to serialize it.

quartz folio
#

That doesn't mean anything

shell scarab
#

the case when you try to serialize a Vector2 to a file. I'm not sure what you mean. I know you can pass a serializer (i forgot exact name) when serializing but I didnt see anything built into unity. I was not trying to use the JSON serializer.

quartz folio
#

Saving what to a file, what format was it serialized into before you decided to write it?

shell scarab
#

a Vector2

#

I was trying to serialize a Vector2

#

how many times do I have to say it

quartz folio
#

That's not a format that can be written to disk, that's a type

cosmic rain
cosmic rain
shell scarab
#

my bad. I first tried to just serialize the Vector2 to a file using a Binary formatter. I also tried to serialize it to a byte array and write that to the file.

quartz folio
cosmic rain
shell scarab
#

yes I know it is not good for security, the compiler literally warns you of that.

shell scarab
#

this is a "how is it done" question

cosmic rain
quartz folio
#

You pass it through a sensible serializer like Newtonsoft.Json, and write it to disk

spring creek
quartz folio
#

In the case of Newtonsoft you also need converters because of the way the type is structured, and I posted those earlier

cosmic rain
quartz folio
#

The YAML serializer reads the data, formats it, and writes it to disk. Just as any serializer does. Is there an actual question here?

shell scarab
#

I guess not knowing how something is serialized and asking how its done is not a question

quartz folio
#

Well you've been answered then, many times

thick socket
#

After 1 hour of debugging

#

Im finally free

warm aspen
#

@shell scarab I think some things would be cleared up if you shared the code that tries to save it to a json but gives an error

#

They are saying it is serializable, so something gives

shell scarab
warm aspen
#

So the question is why are they not marked as serializable?

quartz folio
#

That attribute is a hint for certain serializers, but is not required for many, and Unity does not require it because Vector2 is a built-in type that they natively support without the attribute.

spring creek
#

I guess my confusion came from thinking you thought they were not able to be serialized at all. But you meant universally serializable without an attribute?

shell scarab
#

I suppose. I was just curious about it, but the treatment bc I didnt know some things just turned me off from wanting to know. They aren't marked as serializable, so I thought they weren't serializable. But they're serialized to the inspector. Which is why I asked to a file. There wasn't a need to just make fun of me for saying they aren't serializable when they literally are not marked as serializable. My mistake for thinking this is a place where I can ask questions without being made fun of. Clearly there was a knowledge gap.

spring creek
cosmic rain
#

I think you're jumping to conclusions that everyone here is out to get you. No one made fun of you. We were just trying to lead you to clarify your question or the context of it.

#

I literally can't find anything offensive in the conversation.
Aside from maybe excessive reaction emojis...

warm aspen
#

Looking from outside I felt that you guys were being unnecessarily dismissive of his questions and not making an effort to understand what he was trying to ask or to further explain what you were answering

spring creek
# warm aspen Looking from outside I felt that you guys were being unnecessarily dismissive of...

"try to serialize a Vector2 to a file"
"they are not"
"I guess you guys can't read"
"how many times do I have to say it"

I felt one party was the most aggressive. But ok
We tried to clarify, and correct in the beginning, but there was a hard refusal to help us understand
Our earliest comments were all just trying to understand where they came to that idea. Because all of us have serialized Vectors

warm aspen
#

Is it or is it not marked?

shell scarab
#

I meant to say trying to serialize a Vector2 to a file, sorry. But the immediate responses made me feel the need to be defensive.

cosmic rain
warm aspen
cosmic rain
#

I guess if an appropriate proof was provided early on, it would've solved a lot of the issues in the conversation.

thick socket
#

You will take a little "abuse" at first

cosmic rain
thick socket
#

builds character

#

but dlich is pretty great and has helped me out a bunch for sure lol

warm aspen
thick socket
#

but Sasquatch B Studios seems up to date and has great info imo

#

worth watching some/all of his vids ๐Ÿ˜„

warm aspen
#

Cool

thick socket
#

spent today redoing all my player and enemy AI to make it scriptable objects and my work will be so much faster now lol

quartz folio
#

Posting something without context that is wrong, and doubling down in the face of others is a fast way to make people annoyed

shell scarab
#

Except you didn't ask for proof. Next time if you don't understand a question or it needs more info, a simple "I don't understand your question can you clarify" would suffice. Also, I don't see anything about this channel being only for questions with code you have written, it says "general coding concepts in Unity".

#

I felt I had all the context. I didnt know enough to provide the full context. Which is why just asking for more would have been good since there was a knowledge gap.

spring creek
cosmic rain
# shell scarab Except you didn't ask for proof. Next time if you don't understand a question or...

I asked leading questions many times, but you didn't respond to them:

dlich โ€” Today at 12:00 PM
Who said they're not?
Heroshrine โ€” Today at 12:00 PM
try to serialize a Vector2 to a file

dlich โ€” Today at 12:00 PM
Serialize how? There are many ways to do it.
Heroshrine โ€” Today at 12:01 PM
they are not

dlich โ€” Today at 12:01 PM
What makes you so confident about it?
Heroshrine โ€” Today at 12:02 PM
because when you try to serialze a Vector2 to a file it literally produces an error saying that the type isnt marked as serializable.

Maybe the last message gives some hint, but it's hard to believe it without actual code, error messages.

thick socket
#

Tldr: always post code

quartz folio
warm aspen
#

It's water under the bridge

spring creek
warm aspen
#

It was just a lot of communication mishaps

cosmic rain
warm aspen
#

No one's fault

shell scarab
#

I meant to say "trying". I already apologized, but again I am sorry. I thought it would be known they aren't marked as serializable. I understand the "they are not" is not a good response, I am sorry. I didnt know they could be serialize without being marked as serializable. Again, I don't see anything saying that I need to have a question regarding something I programmed, therefore I did not have code as it was not a "my code is broken plz help" question but a "how do they do this" question.

thick socket
#

Ive got to serialize my massive playerInventory soon...here is to hoping everything has been setup right and I dont have a random "un-serializable" class

warm aspen
#

Using dictionaries?

thick socket
#

Yeah, I think I know the json to use that can handle that tho

#

If not you will see me here soon lol

#

And by soon I mean maybe a week or 2 ๐Ÿ˜„

cosmic rain
warm aspen
quartz folio
#

If you use a third party json library they will tend to be able to serialize dictionaries with no work

livid terrace
#

all I need to store are int bool and float so I'll probably figure things out

nimble dome
#

If I have a few different action maps in my input system, lets say play and pause, what is the best way to get each script using an instance of the input system to reflect the current state of the game?
If I have a input manager, and when the pause button is pressed i want to disable the input system on all scripts using the play action map, and enable all input systems on scripts using the paused action map, how do I go about doing this? Do I use an event?

unborn fern
#

so im having this problem after deleting plasticSCM from my unity game:
NotConfiguredClientException: Unity VCS client is not correctly configured for the current user: Client config file C:\Users\user\AppData\Local\plastic4\client.conf not found. Please execute 'cm configure' to perform a text mode configuration or 'plastic --configure' for graphical mode.
is there any way to get rid of this?

#

nvm i fixed it

frail shoal
#

This code works fine. I simply put in the reference gameobject for the SwitchUnit in the inspector.
But what if I want SwitchUnit to be more than 1 object?
Maybe objects that has a certain tag or rather any gameobject that is specifically in that position in the if statement?
What do I write?

fervent furnace
#

dont cross post, do you know what is array? btw if you have multiple switchunit then you have to change the second if statement

frail shoal
#

what exactly do I write?
I know a bit about arrays but not enough to do this apparantly

cobalt scarab
#

what do you guys think of this approach ? I'm making dictionary for buffs and debuffs some of them have Reference to the dictionary and they can self remove after some time

 { 
     public  event EventHandler<ModifierArg> ModifierHandle;
     public new void Add(string key,IModifier item)
     {
        
         base.Add(name, item);
         ModifierHandle?.Invoke(this, this[key].ModifierArg(true));
     }
     public new void Remove(string key)
     {
         ModifierHandle?.Invoke(this, this[key].ModifierArg(false));
         base.Remove(name);
         
     }
 }```
frail shoal
#

Just want SwitchUnit(it's a game object) to be every single game object in the Unitprefabs array

#

Unfortunately Unity doesn't understand quantum physics where an object can be multiple things at the same time

#

oh shit, maybe I should do a raycast

somber nacelle
nimble dome
frail shoal
#

I watched quite a few C# tutorials on arrays just now

#

Still can't do it.

somber nacelle
#

what are you trying to do? because the code you posted before is almost nonsensical in what it does

frail shoal
#

I want to make it so that you can only switch with cards that you control and not the opponent's but that comes later

#

So if card (A) attempts to go left and there is a card(B) in it's desiredlocation, instead of the method failing, the two cards will switch positions

mild coyote
#

Is it possible to pass a delegate/action as parameter?
Something like this?

//Class ClassA
public void RegisterAction(System.Action<float> action)
{
  action += DoSomethingHere;
}

void DoSomethingHere(float x)
{
  Debug.Log(x);
}

//Class ClassB
System.Action<float> action;
ClassA classA;
...
classA.RegisterAction(action);
action.Invoke(0.5f);//null reference error

Or are there any alternative to that?

simple egret
#

ClassB should expose an event Action<float> instead

#

Then ClassA can subscribe to it

somber nacelle
simple egret
#

Then I guess your RegisterAction method could take a ClassB parameter, and subscribe to the event

mild coyote
mild coyote
nimble dome
# frail shoal Basically, this code works. But the problem is that I have to assign SwitchUnit ...

In terms of the array part. If the amount of switch units stays the same you could manually add them into a list in the inspector, or if not, add them at runtime through code.
Lists are the best for this.
This will allow you to add the objects manually in the inspector.
public List<GameObject> switchUnits = new List<GameObject>();
This will let you add items via code. So you could instantiate them and them add them during runtime.
switchUnits.Add(your gameobject);

#

You could then reference each item via its index or other method

regal epoch
#

I have this code

using System;
using UnityEngine;
using Unity.Netcode;
using UnityEngine.Networking;

public class RandomNumberGenerator : NetworkBehaviour
{
    private System.Random randomGenerator = new System.Random();

    [SyncVar]
    private int randomValue;

    // Server initialization
    public override void OnStartServer()
    {
        base.OnStartServer();
        GenerateRandomNumber();
    }

    // This method generates a random number and syncs it across all clients
    private void GenerateRandomNumber()
    {
        // Generate a random number (e.g., between 1 and 100)
        randomValue = randomGenerator.Next(1, 101);

        // Sync the randomValue variable across all clients
        SetDirtyBit(1);
    }

    // This method can be called by a client to request a new random number
    [Command]
    private void CmdRequestRandomNumber()
    {
        if (isServer)
        {
            GenerateRandomNumber();
        }
    }

    // Client-side method to handle the received random number
    [ClientRpc]
    private void RpcReceiveRandomNumber(int newValue)
    {
        // Handle the received random number on the client-side (e.g., display it)
        Debug.Log("Received random number: " + newValue);
    }

    // Example of how to request a new random number from a client
    private void Update()
    {
        if (isLocalPlayer && Input.GetKeyDown(KeyCode.Space))
        {
            CmdRequestRandomNumber();
        }
    }
}

but somehow it's not working. I don't know why. Could somebody look at it?

somber nacelle
regal epoch
#

oh okay thanks

cobalt scarab
pastel halo
#

Hey, I'm trying to solve this difficult twin-stickish control scheme and I'm having difficulty figuring out the rotateTowards/LookAt code.
The idea is that the horse will face the direction you keypress in (using input.x/input.y from input actions). those values always return absolute -1/1 or 0.71/-0.71

The problem is compounded since you are able to rotate the transform root (entire gameObject) and the WASD is only rotating the child visual (horse). It's dual rotation. Trying to debug out the values to "look at" changes. It seems
Here's the code of just the input: https://pastebin.com/5ZfaSubR
The parent Root rotation is just middle mouse + drag -> totalRotation += context.ReadValue<Vector2>().y)

If the camera didn't rotate, I'd have about half of it solved, since it does technically face the direction you keypress, while the parent transform root stays fixed.

#

the debug was outputting 0.71 and -0.71 as the diagonal, so I tried
if (inputVector.x == -0.71 && inputVector.y == 0.71)
toRotation = Quaternion.LookRotation(transform.forward + -transform.right, Vector3.up);
I was hoping that adding the two transform directions would create the inbetween diagonal so you can face diagonally while running that direction

summer oracle
#

Hi guys,

#

I have a question

#

How is OnApplicationPause and OnApplicationFocuscalled in Editor, Android and IOS, and what are their execution orders.

#

've been messing around with them for a while and there is no clear documentation whatsover on this, which makes me feel a lot confused

frail shoal
#

The answer wasn't arrays at all

#

It was raycast

#

I was supposed to shoot a raycast from the selected unit towards left, forward, back etc so that the secondary unit gets selected so I can have 2 units

stable warren
#

is there anyone that can make a unity game with me

fervent furnace
#

no

#

you should post it in jobcolla !collab

tawny elkBOT
left knot
#

hey me and my friend are wanting to make a game like bit life using unity where have some hardship with getting the basic done like the aging system can any one help with that, i feel like i tried everything but we cant achive that bitlife aging and the years going up fase

knotty sun
left knot
#

no hlep

spring creek
steep herald
#

Struggling to come up with a player FSM logic that makes sense.

For instance, if the player can both jump and attack at the same time, then since only a single state can be active at a time, one of those 2 can't be a state. Which one? How do you reason about this?

swift falcon
#

How can I detect the model of gamepad connected to Unity?
I need to figure out if the model is Playstation so I can change the button names

knotty sun
steep herald
#

@knotty sun Maybe my lack of experience with FSMs but I feel like that'd be a nightmare. If states use self contained logic(mine do), they'd need to cross validate with other active states to determine whether or not they can effectively change.

swift falcon
knotty sun
#

true, each state would need logic to behave appropriately depending on the combined state
i.e. Jumping, Crouching and Attacking

warm aspen
steep herald
#

@warm aspen Yeah, seems like a more sensible design. For jumping, all relevant logic is performed as the input is processed, so this will work perfectly.

For attacking, it seems not so great since attacking is done over a period of time. (e.g. sword swing where there's multiple collision detection steps)

This means that I'd have to, within the attack, constantly keep track of the state to make sure I haven't entered a state that would conflict with the attack (e.g. dead)

I mean, it's not the end of the world but my character controllers have always been absolute messes in the past. Was hoping to do better this time ๐Ÿ™‚

All being said, thanks for your input

warm aspen
marsh marten
#

Not sure if this is proper channel but maybe someone will know the answers

Autocomplete sorting - it shows me a lot of unnecessary suggestions, especially when compared to VSS - how I can get rid of them?

(is it extension's fault? I have active C#, C# Dev Kit and Unity) (edited)

simple egret
#

It probably picked up these because the casing matches exactly. If you wanted transform, you need to keep the first letter lowercase

#

It's the same in VS, it also now suggests types from unimported namespaces by default, but this can be disabled

marsh marten
simple egret
#

Yeah the VS2022 and VSC equivalent of this would be the same as if you hit this

#

It's now enabled by default

#

I don't know if it can be disabled in VSC - search the C# extension settings for a "show items from unimported namespaces" option, or anything named similarly

marsh marten
#

I have bonus question - is it possible to auto insert space after accepting suggestion with Spacebar?
That's another thing that I think is default in VS, but I can't find setup in Code ๐Ÿค”

desert wind
#

For my project, I am trying to make my player automatically jump when they touch an object that is part of a certain layer, the problem is I believe I am referencing it wrong. Here is the code.
https://paste.ofcode.org/b4H6VTTpQeTFU6caRZsMgB

mellow sigil
#

It's comparing a layer and a layer mask. They're different things.

#

Try if((whatIsWall & (1 << collision.gameObject.layer)) != 0)

heady iris
#

LayerMask could really use a nice MaskFromLayerIndex method on it

#

i just don't like seeing the bit shifting for some reason

#

it could also do with union/intersection and "is empty" queries, too

#

wouldn't be hard to make extension methods...

heady iris
#

Right, but this is about getting a mask from a layer ID

#

I guess you could go ID -> name -> mask

knotty sun
#

then you bitshift

heady iris
#

ye

#

I just find it to be unintuitive to look at, compared to everywhere else that you use named methods on LayerMask

knotty sun
#

easy way to solve, make a struct for all 3 values

west mesa
#

what did you say

knotty valley
#

make a reference to your inventory component in your pickup weapons script

#

you should really !learn the basics

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

knotty sun
robust osprey
#

Hello, I am using a ScriptableObject for an audio container, nothing very fancy, originally came from one of Jason Weimann's courses. In one project I can edit multiple instances of this ScriptableObject, and in another project I get the "multi-object editing not supported" message when selecting the same (2 or more) objects. Both projects are on 2022.3.8f1; any ideas why this might be happening?

buoyant ermine
#

so, I have a bunch of invisible unity buttons that need to move about the screen and change size based upon what video is playing, all while being unclickable until pause? any ideas?

sage latch
sage latch
frail ibex
sage latch
#

unfortunately that doesn't work

knotty sun
frail ibex
frail ibex
#

WE are a group of 3 person working on the project and i didn't code PlayerMovement class myself and when i touch something like putting a properties as public static it break the whole code that's link with

#

Get or Set doesn't seems to work either

sage latch
#

Just do player.PROPERTY = ..

#

(provided they're public, but you could just make the public if not)

frail ibex
#

When i set public it break the thing, some are in private

#

To be sure the code for the file itself is good ?

knotty sun
#

no

sage latch
#

What's stopping you from making the properties public?

sage latch
#

What error

frail ibex
#

sec i'm on my phone

frail ibex
knotty sun
sage latch
knotty sun
#

SOLID

sage latch
#

well

#

first it has to actually work

frail ibex
knotty sun
#

post playermovement script

frail ibex
#

It's kinda huge though, it' a mess even i don't want to read it

sage latch
#

What do you want to save?

knotty sun
#

we can't help you with it if we cant see it

sage latch
#

that's the important part

frail ibex
#

Friend made it like that, don't ask why he didn't split in other files

sage latch
#

You should be able to set playerHealth to be public

knotty sun
#

Ok, it's a Monobehaviour, you cannot serialize that

frail ibex
#

How can i fix that ?

frail ibex
sage latch
frail ibex
#

I showed it already

#

Ah

knotty sun
#

make another class and copy the variables from PlayerMoveMeny to that class then use that class in your SaveData

frail ibex
sage latch
# frail ibex

You have to get a reference to a PlayerMovement component, not just use the class name

knotty sun
#

that is not how you reference variables from a class

#

btw I cannot see a single reason why changing any private to public would break anything or cause an error

frail ibex
#

Mh, it break in an another file

knotty sun
#

doubt

frail ibex
#

GetComponent<PlayerMovement>().nbCoin += qg.quest.gold; was this one

knotty sun
#

that is public

frail ibex
#

Then i'm doing it wrong

knotty sun
#

probably not finding the PlayerMovement component or qg is null or qg.quest is null or qg.quest.gold is a incompatible data type, did you bother to check any of that?

frail ibex
#

Nah it made the error when i put nbCoin as public static

knotty sun
#

cannot be static

frail ibex
#

That the only way i found to pull it out, but it didn't work anyway

knotty sun
#

why would you even think of making it static?

#

this GetComponent<PlayerMovement>().nbCoin is how you pull it out

frail ibex
#

No i tried it and not working either

knotty sun
#

did you do the GetComponent on the correct gameObject?

#

seems to me like you need a lot of !learn

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

frail ibex
#

Probably, yes i don't say i'm good, i'm trying to improve also

toxic vault
#

I have this kind of GUI layout where I navigate to various screens by clicking different buttons. Works well for touchscreens and mouse.

But now I am trying to make it work with keyboard/controller and having a hard time keeping track of which button on which panel is currently highlighed/selected so pressing ENTER key or X button triggers the event.

mossy ravine
#

Hello! I have a game where thew player can create levels and I want them to be able to save the levels in the form of JSON files locally. The game is both PC and android, is there a common prefered way to save those files? Or a different way by platform ?

sage latch
#

Be sure to also use Path.Combine when making paths to make it compatible with every os

mossy ravine
#

Fantastic, this is exactly what I was looking for, than you so much @sage latch !

frail ibex
#

Sorry to insist sadly, i don't have much time to pass on the learn unity yet, i'll take time for it when i can. If i can get learn just for my problem right now i'd be happy enough please.

sage latch
#

easy way is to make a public field of type PlayerMovement in the SaveSystem

#

then you can drag the player in

frail ibex
#

public PlayerMovement player = new PlayerMovement(); wasn't this meant to do this somehow ?

sage latch
frail ibex
#

If it's that, was already the case

sage latch
#

Kind of

#

SaveData shouldn't have the reference to the PlayerMovement though, since you can't serialize a component

#

Put the PlayerMovement field in SaveSystem instead, and the data you need to store in SaveData (such as coin and health)

frail ibex
#

Yes i checked the JSON only getting ID

sage latch
#

Yeah

frail ibex
#

Ok, i still get error though

#

Asking for reference, SaveSystem.player

versed loom
#

does someone know how to remove those 2 <No Name> file templates?

frail ibex
sage latch
#

put that code in Save() instead

cobalt scarab
frail ibex
cobalt scarab
frail ibex
#

Yes

frail ibex
sage latch
#

I meant this:

    public void Save()
    {
        data.coin = player.nbCoin;

        string player = JsonUtility.ToJson(data);
        string path = Application.persistentDataPath + "/Save.json";
        Debug.Log(path);
        System.IO.File.WriteAllText(path, player);
        Debug.Log("Sauvegarde effectuรฉ");
    }

```It's a bit confusing that you define the json string as "player"
#

consider switching that

orchid bane
#

Resources.Load asks for folder name but how do I load a file with a specific name?

frail ibex
#

Ah

sage latch
orchid bane
cobalt scarab
sage latch
orchid bane
#

So folderName/fileName?

spring creek
spring creek
sage latch
frail ibex
#

@sage latch Ok seems to work

cobalt scarab
orchid bane
#

Dosc tho: Pathname of the target folder.

frail ibex
#

Got the coin saved on the json

cobalt scarab
orchid bane
#

Do you think it's different?

spring creek
#

Where is that?
I see:
"Path to the target resource to load."
And "Loads the asset of the requested type stored at path in a Resources folder."

Edit: ah, that was already said, sorry

sage latch
spring creek
# orchid bane

Different method. As they said and you know, so just reiterating

sage latch
#

The description says Asynchronously loads an asset stored at path in a Resources folder. so I guess they're a bit indecisive

frail ibex
cobalt scarab
# orchid bane

async load with task so you dont have to wait for the load to finish unlike normal load

sage latch
#

After you load the data

frail ibex
#

Alright, thanks Bobbo !

orchid bane
#

Bobbo!

sage latch
#

thats me

#

happy sunday

frail ibex
frail ibex
#

Harder but possible ?

sage latch
#

Do you have to get the save data in the other scene?

frail ibex
#

My Load button is in an another scene that load the game which is in another scene

#

Basically, i have a Scene for the Main Menu, and a Scene for the Game

sage latch
#

Why not have the SaveSystem in the Game scene?

#

do you need it in the menu?

frail ibex
#

But the button for Loading is in the menu though

sage latch
#

If you call Load from Awake

#

You don't need a button to trigger it

frail ibex
#

So the button for changing Scene, and Awake that load data

sage latch
#

Yeah

frail ibex
#

Okay ! Thanks

torpid sand
#

Hey all, I'm having a hard time figuring out how to get the Timeline Signals to fire during edit mode. I found some examples online about using NotificationFlags, but I can't for the life of me figure out how to use it or how to make a script that could replace the original SignalAsset or SignalEmitter

#

Sooo any help or ideas very welcome

robust osprey
# sage latch Do you have an custom editor in the one but not the other?

I definitely have custom editors, but they're in both projects and the objects themselves are fully editable. I did previous have a Unit Test framework in the new project (where multi-edit is not working). I got into such a mess with that, I had to undo it all and remove all the Assembly Definitions (even though the testing itself was great and worked). Anyway maybe in the undoing of it I broke something. Unfortunate! Thanks for the reply.

heady iris
#

oops, hit enter early

#

Also I just answered my own question while typing it out. So, all good ( :

orchid bane
#

I have this

File.WriteAllText($"{ScenesPath}/" + sceneName + ".json", json);

but it doesn't work if the file isn't created yet, what do I do?

hard viper
#

How do I load a json file in the projectโ€™s build? ie how do I target it via path?

vital jackal
#

Iโ€™m trying to get authentication set up and Iโ€™m a bit confused. Thereโ€™s a method called SignInWithSteamAsync(string ticket, string identity, SignInOptions options = null) What am I supposed to pass in for identity and sign in options? Documentation says โ€œidentity of the calling serviceโ€ for identity and โ€œoptions for the operationโ€ for the sign in options.

heady iris
#

you could reference it, or load it from Resources

#

If you really need to have an actual json file on disk, then you'll need to put it in StreamingAssets

heady iris
calm talon
#

How do I check if a collided object's layer is contained within a layermask?

glad locust
#

I'm trying to get the metadata for my IAP so I can show the price to people before clicking the button. This used to be easy to access with the legacy codeless IAP but now I'm forced into using the new stuff. According to documentation, I have to access the IStoreController interface. I'm not particularly good at understanding interfaces but adding this one gives a lot of errors asking me to add a bunch of functions to my class to take care of the various things the interface can do. 1: Is there an easy way to automatically add all of these necessary functions and/or 2: Is there a way to use interfaces without it asking for all the functions (that I won't be using) to be added to the class?

Edit: Turns out right clicking on the interface's name and selecting the lightbulb actually adds the entire function set. Amazing. This answers my first question at least.

nimble dome
#

Does anyone know how to avoid getting the "A constant value is expected" error when using a InputAction in a switch?

    {
        switch (ctx.action)
        {
            case playerInputActions.CharacterMovement.BuildMode:
                Debug.Log("true");
                break;
        }
    }```
flint kettle
#

I'm trying to make a custom character controller for my 2D platformer, I have watched many of tutorial, they divided "player velocity" and "gravity" into two variables, one store player movement, another store gravity velocity, but when player jumps, "player velocity" will be (0,10) , and since gravity is independent to "player velocity", so (0,10) won't be reduce by gravity, how can I solve this kind of problem ?

leaden ice
nimble dome
#

or rather else if

orchid bane
#

I'm creating objects in Edit Mode but how do I make them dirty so that I can cancel them later?

#

Undo.RecordObject looks like doesn't work on not created objects

nimble dome
orchid bane
leaden ice
nimble dome
#

thanks ill look into it

quartz folio
orchid bane
flint kettle
nimble dome
#

true but you could fix that with grounding

#

You would also want to stop subtracting velocity when you are grounded to it doesnt continue to drop even while on the ground

flint kettle
#

you mean set gravity to zero when grounding, so it won't keep subtracting velocity?

hard viper
#

are you working with slopes and a dynamic rigidbody?

flint kettle
hard viper
#

nvm then. there should be many tutorials for that

#

i did work with dynamic ones, which is a lot harder

#

forces in general shouldnโ€™t affect kinematic rigidbodies, including gravity

flint kettle
hard viper
#

thatโ€™s not hard. just use kinematic equations and basic physics

#

if you are on ground AND you shouldnโ€™t be disconnecting (ie jumping, swimming, big force applied etc), set no gravity

flint kettle
rocky basalt
#

How could one set an enum using an index? As in, I want to set it to the enum's 3rd value, for example.
myEnum = MyEnum.IndexOf(3); (fake code but this is what I want to do essentially)

prime sinew
#

Enum aren't indexes

#

They're just int

waxen burrow
#

Hey, im trying to work with the kiwicoder behavior tree, and im running into an issue where it wont accept public / serialized properties from the inspector. I dont know if anyone can provide some advise or if I'm just going to have to pony up for a real BT asset.
The issue is a little tough to but into writing but in short, its just like making a public or serialized property in a normal script, where it appears in the inspector and you can select an object of a specific type from the field. Except when you select an object from that field it errors out and says that there is a type mismatch, when you literally can't select an object of the wrong type

heres a video of it as well
https://cdn.discordapp.com/attachments/1146187317502029917/1154870484362612736/20230922-2002-19.6366722.mp4
ignore the poor naming, I did this in a different project to double check it wasnt a bug caused by a bad library

teal knot
#

any ideas how i can get the position of each corner of the pink area? its created by overlapping 3 different coloured ui rectangles (red yellow blue) and i was hoping there was some math i could do find the exact position and size of the pink overlapping area

neon junco
#

Talking to ChatGPT I found a solution to the ever annoying task of using Compare Tag and not using the correct string name.

Just use this in an empty script:

https://gdl.space/toviyufuca.cs

Than when you create a variable using any string just have [TagSelector] [SerializeField] private string than your variable name.

In the inspector it will now have a drop down box using the already made tag list you made in the inspector.

I Understand most don't use compare tag but others that do might find this useful so there is no error mistakes and the only thing you need to add to your scripts is just [TagSelector] [SerializeField] to access it.

granite wolf
#

I would like to ask if there is a way to have the ScrollView's Content's size automatically adjust according to the size of the sub-objects without using any LayoutGroup? Although LayoutGroup+ContentSize solves the problem, I don't want to have the LayoutGroup automatically resize the sub-objects

fair wadi
#

Hello! I am using github with unity to have two people working on one project, I just tried to do a commit but it said I was unable to as it was over the 100MB limit, what should I do to fix this issue?

quartz folio
#

!vc

tawny elkBOT
#
Using version control in Unity

โ€ข PlasticSCM
โ€ข Git: Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory

fair wadi
fair wadi
#

Okay, thank you!

hidden parrot
#

No idea but why would you want them to fire in edit mode

torpid sand
#

I found a better solution though, making them with timeline tracks instead of signals

gray mural
#
public virtual IEnumerator Collide(ItemBehaviour collision, Vector2 expectedPos)
{
    print($"Collide - {name}");
        
    yield return null;
}
public override IEnumerator Collide(ItemBehaviour collision, Vector2 expectedPos)
{
    base.Collide(collision, expectedPos);

    print("yep, collided");

    if (collision.itemType == ItemType.Player)
    {
        print("yep, player");

        collision.transform.position = expectedPos;

        GameManager.PlayGame(false);
    }

    yield return null;
}

Hello, any ideas how to make override Collide not to be interrupted by virtual Collide ?

#

I need'em to be coroutines, I'll implement further logic after that

hidden parrot
#

Can you StartCoroutine it instead of calling it

#

I know you can yield startcoroutines, maybe thats whats happening here

torpid sand
#

Yeah just guessing, but maybe StartCoroutine(base.Collide(collision, expectedPos))

#

You might end up with two simultaneous coroutines tho

hidden parrot
torpid sand
#

So as frant said, yielding the base coroutine first might work

hidden parrot
#

I assume by interrupted he means the coroutine stops for the base coroutine to be called

torpid sand
#

It probably doesn't "stop", it just never gets properly started

hidden parrot
#

Right, interrupted is pretty unclear here
Anyhow, startcoroutine is the first thing no matter what

gray mural
#

oh, it seems not to collide at all

public override IEnumerator Collide(ItemBehaviour collision, Vector2 expectedPos)
{
    print("Hole - Collide");

    yield return StartCoroutine(base.Collide(collision, expectedPos));

    print("yep, collided");

    if (collision.itemType == ItemType.Player)
    {
        print("yep, player");

        collision.transform.position = expectedPos;

        GameManager.PlayGame(false);
    }

    yield return null;
}
#

it worked yesterday, gotta check my git commits that have broken it

torpid sand
#

Who's calling Collide to begin with?

gray mural
#

a player

torpid sand
#

How?

gray mural
#
protected void CallCollisions(ItemBehaviour[] items, Vector2 expectedPos)
{
    foreach (ItemBehaviour item in items)
    {
        if ((item.itemType & collisions) == 0)
            item.Collide(this, expectedPos);
    }
}
#
// Player.cs
CallCollisions(items, newPos);
torpid sand
#

Should that be a StartCoroutine as well?

#

This one item.Collide(this, expectedPos);

gray mural
#

I haven't mentioned it

#

thank you!

torpid sand
#

๐Ÿ™‚

gray mural
#

now it works, what a stupid mistake of mine

torpid sand
#

Hehe it happens

#

Looking at your code snippets, there's nothing that requires them to be coroutines though. You sure you need them?

gray mural
#

thought it happened because of yield break before, then changed to yield return null, gotta change back so that it won't wait a frame

gray mural
torpid sand
#

Alrighty

torn eagle
#

Might be a bit of a stupid question but is there a way to reference children of a parent class using GetComponent<>? For example if Potion derives from Item I would still be able to access it by saying GetComponent<Item>?

torpid sand
#

You can cast it

#

For example
(Potion)GetComponent<Item>()
or
GetComponent<Item>() as Potion

torn eagle
#

Ah my problem is I have multiple items

#

So like, if Potion and Stick were items I could reference either one through GetComponent<>

#

Actually I could probably just add self-destruct functionality through casting anyway

torpid sand
#

Hmm I don't really understand what you're after

#

You could cast as Potion or Stick?

torn eagle
#

Oh wait no that still wouldn't work

torpid sand
#
var stick = (Stick)GetComponent<Item>()```
torn eagle
#
 Component component = itemHolders[val].GetComponent<InventoryItem>();
        Destroy(component);```
dusk apex
#

What're you trying to do specifically?

torn eagle
#

Essentially trying to destroy any components of the Item class

torpid sand
#

What do you think are the "components of the Item class"?

torn eagle
#

Oh sorry of the InventoryItem class

torpid sand
#

Same question

torn eagle
#

Any script inheriting from it

torpid sand
#

Then your script basically should already work

torn eagle
#

It's not seeming to destroy it though so I feel like I'm goofin up somewhere

torpid sand
#

If Potion inherits from InventoryItem, and you find all components of type InventoryItem, it should return Potion as well

torn eagle
#

Wait oh my god I see my issue now sorry lol

#

I wasn't destroying it from the right object

#

I'm so sorry to waste your time oh my godd

torpid sand
#

Heheh

urban lintel
#

is it sensible to use a coroutine to reduce the frequency of calls that may(?) be expensive? I have a script that tries to find the enemy player based on certain conditions (distance, maybe sight of vision at some point) but i figured there's no real reason to run this every single frame and that running it like 5-10 times a second is enough, is running this on a coroutine and setting a wait for 0.1-0.2 reasonable?

torpid sand
#

I do that sometimes too, but it feels iffy

#

If it truly is a heavy operation, you might end up calling them in sync for multiple enemies and causing a lag spike whenever it hits

urban lintel
#

that's a good point, although i imagine that's still equally or less expensive than if it ran every frame too

torpid sand
#

Not sure about your level of development, but if you're not experiencing any issues with performance, my advice would be to not care about performance until you can visibly see a performance issue

urban lintel
#

yeah i'm far from having them as issues, just was curious if that's something people use them for or not

torpid sand
#

And once you do, use the profiler to see what is actually causing the perf issues

#

But a couple of raycasts every frame is nothing, if you're worrying about something like that

#

If your sight of vision area can be a box or a sphere, you could do it all with trigger colliders with OnTriggerEnter / Exit

#

(or a capsule...)

vagrant plaza
#

whats wrong?

torpid sand
#

Maybe .SetBool("IsJumping", true)

vagrant plaza
#

YEAH

#

damn it

#

thx

gray mural
#

Any ideas why this method breaks unity (so that I have to close it via Task Manager) when there are just 13 items in itemData?

public void LoadLevelData(string levelId)
{
    LevelData levelData = GetLevelData(levelId);

    if (levelData != null && environment != null)
    {
        List<ItemData> itemsData = levelData.itemsData;

        foreach (ItemData item in itemsData)
        {
            GameObject newItem = Instantiate(GameManager.instance.GetItemByName(item.name), environment);

            newItem.name = item.name;
            newItem.transform.position = item.position;
        }
    }
}
#

this couldn't be performance issues, right?

#

it just spawns 13 GameObjects

somber nacelle
#

are you sure this is the code that causes the issue?

gray mural
#

I have just tried to spawn just 1-4 items and unity didn't seem to broke

somber nacelle
#

well it's either that you are spawning something that has an infinite loop or spawning something that spawns itself that spawns itself that spawns itself etc

gray mural
somber nacelle
#

no, that wouldn't cause unity to completely lock up forever. that would just cause things like reduced frame rate

gray mural
#

I see, is there any wait just to pause the game when it breaks?

somber nacelle
#

use breakpoints

gray mural
#

in order not to restart unity every time

gray mural
somber nacelle
#

use them to pause execution. you know, to stop your infinite loop

gray mural
#

but I don't know where my infinite loop is..

somber nacelle
#

then do nothing i guess, i don't know what you want me to tell you other than that you need to debug your code to find the source of the issue

gray mural
#

guess no then

somber nacelle
#

yeah you can prevent unity from "breaking" by not writing infinite loops. otherwise you'll need to use breakpoints and debug your code to find the source of your infinite loop(s)

gray mural
#

I see, I'll try to find them, thank you ๐Ÿ˜„

thick socket
#

do I need class to be monobehavior to use

#
_timer += Time.deltaTime;
prime sinew
#

but if you plan to run that in Update, then yes?

#

you need MonoBehaviour to have Update

thick socket
#

Gotcha, was planning to make a class that does attacks in update

#

but a "helper" class that has all the code for each attack of attack that wouldn't need to be a monobehavior

rain minnow
simple sable
#

Hey. So, I have this enum declared as public, outside of any class, because I want it to be accessible from anywhere in my game, by all scripts.

This enum contains all the directions an entity in my game can face. However, the only problem I'm facing is how to associate a Vector2 with each of those directions. I want to be able to access the correct Vector2 that an entity should use to move, based on the direction. I'm just not quite sure how to approach solving this issue.

thick socket
simple egret
#
// In STATIC class
public static Vector2 AsVector2(this FacingDirection dir) => dir switch
{
    FacingDirection.North => Vector2.up,
    // etc.
}

Usage:
Vector2 v = FacingDirection.North.AsVector2();

rain minnow
leaden ice
#

ah sorry i was slow

#

very similar to SPR2's

simple egret
#

Mix of both, not sure which is more performant

leaden ice
#

they're probably similar. I think the switch becomes a jump table at some point

simple egret
#

Yeah it has 8 cases so probably becomes a jump table

thick socket
#

I feel like Im doing this a bad way...

#
public class MyMeleeWeapon : MonoBehaviour
{
    public string shooterTag = "";
    [SerializeField] Fighter fighter;
    private void OnTriggerEnter2D(Collider2D collision)
    {
        var tag = collision.transform.tag;
        if ((tag == "Fighter" || tag == "Player") && tag != shooterTag)
        {
            Fighter colFighter = collision.GetComponent<Fighter>();
            colFighter.Damage(fighter.stats.attackDmg);
        }
    }
}```
#

Is there a better way to be doing this?

simple sable
#

Oh, thank you so much guys! That's very helpful.

becomes a jump table
What does that mean (if you don't mind answering)?

thick socket
#

essentially Im wanting to grab the fighters dmg and objects tag(to make sure its not colliding/dmging itself)

#

but the Top Fighter(Grim Reaper) will need to grab this script(to enable/disable dmg) and this script will need to grab the Fighter script to work

#

secondary question...when I dont want the script to do dmg...should I just disable the collider trigger, or set a bool in the script to not do dmg?

simple egret
# simple sable Oh, thank you so much guys! That's very helpful. > becomes a jump table What do...

It's in the produced "machine code" C# compiles to. It's an optimized way of moving the execution to a different instruction, so it will probably:

  1. convert the enum value to a number from 0 to 7 (one per direction)
  2. use that number to move the execution to [the current line + the number representing the enum value]
  3. create the vector on the instruction it falls on
  4. return it
    It's like the dictionary, but a low-level representation of it, known when the compiler goes over your C# code
simple egret
#

Yep, but made in the IL code C# compiles to

wispy depot
#

I feel like im probably very dumb here but its telling me that hit might not be initialized and wont let me compile.

RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, hit))
{
    if (hit.transform.gameObject.GetComponent<Planet>() != null)
    {
        selectedPlanet = hit.transform.gameObject;
    }
}
simple egret
#

Initialize variable inline: if (Physics.Raycast(ray, out RaycastHit hit))

#

You'll then immediately see where you're trying to access it where it's not available

simple sable
simple egret
# simple sable That's very detailed, thank you for the explanation!

Made the test on an online compiler, it indeed does a jump table because there are enough enum values.
For input code (image 1), produces a jump table switch IL instruction (image 2) and all its corresponding cases where it loads the numbers (instructions the arrows point to, ldc.i4.* - "load integer number")

#

(the last cases are cropped but it goes on below)

urban lintel
#

i've began to refactor my enemy movement code into using a state pattern, but running into an issue. My previous logic for patrolling was to create a coroutine that travels in some direction, waits X seconds, and then travels in another way, but apparently i can't use a coroutine in a class that doesn't inherit from monobehaviour. What's a good way to remedy this

rigid island
urban lintel
#

i do have a statemanager (monobehaviour) that has references to the states, should i just add a function inside statemanager that allows for creation/termination of coroutines and call that from inside the states?

simple sable
rigid island
urban lintel
#

i tried doing just stateManager.StartCoroutine but got this after

#

actually this might be unrelated, lemme read some more lol

simple egret
urban lintel
#

ok yeah nvm fixed it, doing stateManager.StartCoroutine works fine ๐Ÿ‘

rigid island
#

niice

kind cipher
#

Greetings. I'm in a 2D gamejam.

I've been fighting this bug for the whole jam.

I have a sprite moving down.

There is a sprite below it with a boxcollider2d.

They are on the same layer.

They are siblings.

This raycast2d is happening in a coroutine.

But, the racast2d never hits anything.

foreach (Transform sprite in currentSprites)
{
    Debug.Log(sprite);
    RaycastHit2D hit = Physics2D.Raycast(sprite.position, new Vector2(sprite.position.x, sprite.position.y - 1), 10f, 8, 9f, 10f);
    if (hit.collider != null && !currentSprites.Contains(hit.collider.transform))
    {
        Debug.Log("Hit Collider.");
        audioSource.Play();
        StartCoroutine(MiniGameResolved());
        yield break;
    }

}
leaden ice
#

That's almost certainly wrong

kind cipher
leaden ice
#

because that parameter needs a layer mask

#

not a layer index

kind cipher
#

oh! right!

leaden ice
#

The easiest way to deal with layer masks is:

public LayerMask myMask;```
kind cipher
#

๐Ÿคฆ

leaden ice
#

define it in the inspector

thick socket
#

What you did makes sense to me lol

#

But Unity says no

rigid island
fair wadi
#

Hello! I was trying to commit my project to github but recived the above error, one person said this was because of the fact that I did not have a .gitingore file, yet I have one in my github

simple egret
#

But do you have the gitignore locally?

#

It won't do anything until it's aside your Assets folder on your filesystem

#

It's configured a special way, so it needs to be at your Unity project root - looks like it is the case here, at least on the remote repository

fair wadi
simple egret
#

You'll see it on your computer as a file, using your file explorer

fair wadi
#

like this?

simple egret
#

Yes

#

Can you show hidden folders? Seems like something is missing here

#

Display > Hidden Elements check box at the top

#

There should be your Git root (a folder named .git) along these

#

Like this

#

Not sure why the C# solution and project files don't appear either on your side

fair wadi
#

I showed hidden items but nothing changed

simple egret
#

I wonder where your Git root is, then, maybe one folder above?

fair wadi
#

like that?

leaden ice
#

Based on this image the root is in the fodler that contains the project and some other folder

leaden ice
# fair wadi

yeah looks like you put your git root one level higher than it should be

fair wadi
#

okay, so move that folder into the FBLA one?

leaden ice
#

i would delete it

#

and do git init inside the project

#

idk what the FBLA folder is

fair wadi
#

could I just move it

leaden ice
#

or how it's relevant here

fair wadi
#

The FBLA folder is where my game is locaed

leaden ice
#

no your game is located in "My project"

#

or rather

#

this might be two different projects

fair wadi
#

Yeah I think it is in the FBLA folder

leaden ice
#

yeah this is definitely multiple projects

fair wadi
#

yeah... so what sould I do?

leaden ice
#

for simplicity I recommend only having one project per git repository

fair wadi
#

Yeah okay I think I messed that up

#

okay so I deleted the "My Project"

simple egret
#

Now you can pull the whole contents of FBLA onto the git root one folder above

fair wadi
#

okay

simple egret
#

The gitignore should now be at the same level as the .git folder, and Git will pick up a lot of "moved element" changes

#

And ignore the useless stuff like the Library folder, hopefully

#

Do note that once you commit and push your changes to GitHub, the "My Project" folder there will also be deleted!

fair wadi
#

so like this?

#

Yeah there is nothing really in there so it is fine

simple egret
#

What, no look at the screenshot I posted

fair wadi
#

so what did I do wrong

simple egret
#

You moved the folder into the git folder

fair wadi
#

Yeah

#

Oh I see

simple egret
#

Move the contents of FBLA 2023-2024 Unity into Documents/Github/FBLA-2023-2024/

fair wadi
#

Okay

#

then can I delete the FBLA folder?

simple egret
#

It'll be empty, so yep

fair wadi
#

okay

#

So like this

simple egret
#

The first 5 files indicate you're still in the .git folder

leaden ice
#

yeah you've really messed something up lol

#

you shouldn't be poking around inside .git typically

simple egret
heady iris
#

I'm deciding how I'm going to name states for different state machines. I have two choices:

  • Make every class name unique. LocomotionIdleState, for example
  • Use the same names, then use namespaces. IdleState in the namespace MyGame.States.Locomotion, for example

The second one seems nice, but then the component's name in the inspector is just IdleState.

Perhaps I need an editor extension that displays the namespace?

I am also concerned about not being able to immediately tell what kind of state something is, though. I'd just have IdleState in the code with a using MyGame.States.Locomotion up top.

#

MyGame.States.Locomotion.IdleState would be a bit too much, lol

fair wadi
#

Like this?

heady iris
#

This is how it should be laid out, yes.

#

The folder you're currently in is the root directory. It contains the hidden .git folder, the .gitignore file, and then whatever folders or files are part of your project.

#

Also, is this in OneDrive or something? You've got that "Status" column.

#

you'll have a lot of churn from all the .git files being backed up, and if you have more than one device, modifying the files elsewhere would cause Surprise Changes

#

i don't think Git would appreciate that

fair wadi
#

Okay I finally GIT it now thank you!

heady iris
#

btw, you can put a .gitignore wherever you want in the project

#

it affects the folder it's in (and any children of it)

#

i haven't actually used that in practice yet, but it could make things simpler if you have weird requirements

tired rock
#

public IEnumerator Roll()
{
Physics2D.IgnoreCollision(GameObject.FindWithTag("EnnemyHit").GetComponent<Collider2D>(), Collide, true);
canRoll = false;
canbehit = false;

    Vector2 rollDirection = new Vector2(xMovement, yMovement).normalized;

    rb.velocity = rollDirection * rollSpeed;

    yield return new WaitForSeconds(rollDuration);
    Physics2D.IgnoreCollision(GameObject.FindWithTag("EnnemyHit").GetComponent<Collider2D>(), Collide, false);
    
    rb.velocity = Vector2.zero;
    canbehit = true;

    yield return new WaitForSeconds(rollCooldown);
    canRoll = true;
}

The roll Dont ignore Any of the EnnemyHit Tagged Object , may someone help me please ?

heady iris
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

(small blocks like this just need the inline-code treatment)

heady iris
tired rock
#

Oh , Is there an alternative ?

heady iris
#

I'd put all of the enemies on an Enemy layer, and put the player on a Player layer

#
Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("Enemy"), true);
#

note that I used LayerMask.NameToLayer, not LayerMask.GetMask. GetMask is not used here.

tired rock
#

Oh : Thanks !

heady iris
#

note that you will want to look at the Physics 2D settings if you need to turn collisions on or off between layers

kind cipher
heady iris
#

but in this case, you probably want both the player and enemy layers to collide with everything else

#

(so that you don't fall through the floor)

tired rock
#

Yes haha

#

Dont want it to fall into backrooms

#

Thanks , it works as intended !

undone mesa
#

Hi guys! I have a simple problem but I can't seem to find the error... I have a script attached to a Canvas object but when I try to access the varaible containing a Slider, I can't seem to do it.

Here my code:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

using System;

public class UIMenu : MonoBehaviour
{
    public Button getBack;
    public Slider slider1;
    public Slider slider2;
    // Start is called before the first frame update
    void Start()
    {
        Button button = getBack.GetComponent<Button>();
        button.onClick.AddListener(PlayGame);
    }

    private void PlayGame()
    {
        PlayerPrefs.SetInt("sensitivity", Mathf.FloorToInt(slider2.value));
        PlayerPrefs.SetInt("levels", Mathf.FloorToInt(slider1.value));
        SceneManager.LoadScene("Game");
    }
}
undone mesa
#

Ohh sorry, i forgot to share the error ๐Ÿ˜…

simple egret
#

Side note, you don't need the GetComponent in Start. Your field is already of Button type.

undone mesa
#

Oh thanks!

knotty sun
#

Are you sure you dont have 2 UIMenu scripts enabled?

simple egret
#

And as for the error, since your screenshot here shows that all fields are assigned, my guess is that you have another UIMenu script elsewhere that doesn't have the fields assigned, and that's the one throwing the exception

#

Search for any other using the Hierarchy search bar: t: UIMenu, as well as in prefabs if you're instantiating these in

heady iris
#

clicking the error might take you to the offending object

undone mesa
trail ferry
#

Is there a way to enable/disable a component in a script (not at runtime level but during editor)

trail ferry
#

Uhh, but monobehaviours only work at runtime, right?

knotty sun
#

no

#

I suspect you are looking for the ExecuteInEditMode attribute

trail ferry
heady iris
#

or [ExecuteAlways], to make it work in prefab mode as well

scarlet viper
#

am i doint this incorrectly?

        float speed = 0.005f;
        float t = Mathf.InverseLerp(from, to, ring.localPosition.y);
        smoooooth = Mathf.SmoothStep(from, to, t);
        float smoothSpeed = speed * smoooooth;
#

basically here smooooth variable is equal to ring.localposition.y

#

and theres no smoothing

#

Does the t parameter go from 0.0 to 1.0 ?

spring creek
scarlet viper
#

but im not sure what im doing wrong. in other script i did a test from 0 to 1 and it works there

        if (isWorking)
        {
            var pos = transform.position;

            pos.y = Mathf.SmoothStep(0f, 1f, t += 0.001f);

            var ss = (pos - cachedPosition).magnitude;
            Debug.Log(ss);
            transform.position = pos;
            cachedPosition = transform.position;
        }
thick socket
scarlet viper
#

the top code doesnt work but the code i posted now does

mellow sigil
#

I don't really understand what you're trying to do in the first snippet

torpid sand
#

GPT seems to know shit tons of Unity. The other day I asked it to create scripts so that I can make custom tracks on the timeline and it provided almost out of the box. And timeline is very badly covered when googling

mellow sigil
#

t is expected to increase linearly, but you're inserting the object position which does not change linearly

#

just increment t like you do in the second snippet

thick socket
#

unity does that great in 3d but its 2d doesn't exist

torpid sand
#

You mean it doesn't know Unity's 2d "helper" functions?

#

Like LookAt in 3d etc

latent latch
#

I find it decent for shader stuff but that's less specific to unity

torpid sand
#

So far I haven't had a topic where it wouldn't be at least somewhat useful

#

And always so friendly too

scarlet viper
#

ahh i see, my issue was

#

i was multiplying speed by smoothstep value
so even if it smoothed ends, the speed was going to be bigger every time near the max value

cold willow
#

For reference this is the script I will be talking about https://pastebin.com/PMp6HMd5

In that script you will notice the functions for Log In, Sign Up, Reset Password, and a few others. Those functions you don't have to worry about they just are functions for telling a service I use called loot locker to sign in players into their accounts. At the top of the page I am declaring variables for tmp input fields that are used to specify the emails and passwords for the sign in and login functions. Then under that I have 3 functions that get called on update that take the input fields .text and set it equal to a string that is used to log in and sign up. Upon testing this in my game on desktop, it works just fine and normal. Upon testing this on webgl, I am able to type in the input fields and everything but upon clicking the log in button, I am told that the email was never specified. Meaning that the email variable for logging in was just nothing even though that variable as getting set to the .text value of the input fields. It may be more than just the email if may also be the password, not sure. Any idea why this could be happening?

gray mural
#

What method is called when player exists the game? (also when I exit it in unity using play button)

cold willow
#

void OnApplicationQuit()
{
Debug.Log("Application ending after " + Time.time + " seconds");
}

gray mural
#

it doesn't print anything

cold willow
#

What platform are you on?

gray mural
#

Windows

cold willow
#

Are you building to windows?

gray mural
#

actually I have forgot to save changes is VS, OnApplicationQuit works now ๐Ÿ˜…

#

thank you ๐Ÿ˜„

cold willow
#

Lol, it happens to everyone. Glad you found your issue!

torpid sand
#

That's the hardest thing to debug remotely; you've done everything right but you haven't saved your files...

thick socket
torpid sand
#

Well... Yeah

thick socket
torpid sand
#

Hehe

#

You could ask GPT to provide you with the math on how to rotate a 2d object's axis to point towards a point within Unity context

thick socket
#

thats what I was trying to say that I did ๐Ÿ˜„

torpid sand
#

Hmm okay ๐Ÿ™‚ I'm a little lost but no worry

#

Did you pay respects to me?

#

(isn't that what F stands for...)

heady iris
torpid sand
heady iris
#

are you having problems with it behaving weirdly when looking at something close to the up-vector?

torpid sand
#

Why not utilize a tool that provides really good starting points and tips for almost anything you do

heady iris
#

because it will emit plausible-looking garbage that just confuses and misleads someone who doesn't know how to spot it

#

LLMs generate plausible text, not correct text

torpid sand
#

So do developers

heady iris
#

yes, which is why I prefer to not add more spam to my plate

somber nacelle
#

"i learned wrong on purpose!"

heady iris
torpid sand
torpid sand
somber nacelle
torpid sand
#

Why would it be "wrong" information if you get the tips and/or examples you were looking for that you can use to speed up your development?

#

Obviously you shouldn't ask it to provide you with the full code for you game

heady iris
#

it is a tautology: if you know enough to fix AI-generated spam, you didn't need the AI-generated spam

torpid sand
#

You're very black and white about the topic

somber nacelle
heady iris
#

end of story. don't tell someone to "go ask GPT"

torpid sand
#

Have you even tried to use it to your purposes?

spring creek
#

I third the idea the chatgpt is terrible for making scripts beyond just doing some boilerplate you're too lazy to physically write yourself, but DO know exactly HOW to write. We spend a LOT of time helping people dig out of the hole chatgpt dug them into.

torpid sand
#

I mean if that topic is not accepted on the server as discussion, then sure I'll shut up

heady iris
#

only to be told that, surprise, it's garbage because ChatGPT spewed it out

somber nacelle
# torpid sand Have you even tried to use it to your purposes?

last time i decided to use it the information it provided to me was incorrect so i had to go and do it myself which was something i wanted to avoid at the time which is why i used it in the first place
and it's not like i asked it something difficult. it was a fairly simple math problem

thick socket
heady iris
#

The code looks plausible, but then it's just nonsense that doesn't do anything

spring creek
#

I've used it dozens of times. Each time was just... useless. It would have been faster to google it. and yes, that includes 4.

It LOOKS fine, and might work superficially. And that is the danger

torpid sand
#

Alright. Well I'm not new to coding and I've utilized GPT's help tens of times and every single time it has been a help to some extent. So I'll just keep on doing that and you can keep on not doing it.

heady iris
#

just learn to read and search documentation. you'll get what you need.

somber nacelle
heady iris
heady iris
gray mural
somber nacelle
# torpid sand Did I say I'm new to coding?

somehow slipped right past the "not" in that sentence. my bad. now imagine if i were an AI and just ignored that. that's what you're getting when using spam generation tools

torpid sand
#

Well, there's no need to discuss this any further. I'll just keep on doing that and you can keep on not doing it.

thick socket
#

however it typically gets you close enough to just need a few tweaks

gray mural
thick socket
#

saving me a lot of time when using functions I haven't done much with before

somber nacelle
torpid sand
#

I don't think anyone said that in response to someone's question

spring creek
#

I scrolled up to find it, and in the process of linking it, hawk deleted it lmfao
It said it was good for math

somber nacelle
gray mural
#

neither do I think I have answered or asked questions using ai

thick socket
torpid sand
heady iris
#

this works correctly in 2D

#

e.g. transform.right = target.position - transform.position;

cold willow
#

For reference this is the script I will be talking about https://pastebin.com/PMp6HMd5

In that script you will notice the functions for Log In, Sign Up, Reset Password, and a few others. Those functions you don't have to worry about they just are functions for telling a service I use called loot locker to sign in players into their accounts. At the top of the page I am declaring variables for tmp input fields that are used to specify the emails and passwords for the sign in and login functions. Then under that I have 3 functions that get called on update that take the input fields .text and set it equal to a string that is used to log in and sign up. Upon testing this in my game on desktop, it works just fine and normal. Upon testing this on webgl, I am able to type in the input fields and everything but upon clicking the log in button, I am told that the email was never specified. Meaning that the email variable for logging in was just nothing even though that variable as getting set to the .text value of the input fields. It may be more than just the email if may also be the password, not sure. Any idea why this could be happening?

somber nacelle
#

I'm curious why you need the Update method at all. just grab the content of those input fields when you need to log in. and make sure you're checking that they aren't empty or null using string.IsNullOrWhitespace

cold willow
#

I had that aswell. I changed my login parameters to just take the .text value of the tmp input field and got the same error.

#

I even tried directly setting it the value of the input field, I dont think this is an error with loot locker because it works just fine with other platforms.

somber nacelle
#

okay and what debugging steps have you taken?

#

also keep in mind that in your Start method you're calling LogIn whether playerprefs has those keys or not. you also don't bother doing any handling for when your variables are null, you still attempt to log in instead of throwing an error or logging useful info

#

and since 90% of the variables in this class are public, that means anything can change them

heady iris
#

that seems weird.

somber nacelle
#

the entire setup is pretty weird tbh. but calling LogIn from Start appears to assume that they have saved credentials in PlayerPrefs (which is also not a great idea)

heady iris
#

"polling" like that gives you room for inconsistencies

#

it can get really bad if there are several steps involved (possibly across several objects)

#

imagine if A sets B and B sets C and C sets D

#

you could get up to three frames of latency depending on execution order

gleaming vessel
#

Hi everyone. Trying to make communication between game and website. I make a webGL build and give it to guy who makes a call to my game from website. However, it doesn't call current function and I can't understand why. I can send info from Game, but can't get it. Here is example of code in JS and my code in Unity

thick socket
#
if (_currentVelocity.x > 0.2f || _currentVelocity.x < 0.2f)
        {
            character.SetState(CharacterState.Run);
            Debug.Log(_currentVelocity + "X Current Velocity");
        }

(0.00, 0.00, 0.00)X Current Velocity is what debugs....how!??!

somber nacelle
#

is 0 less than 0.2?

thick socket
#

gosh darnit

#

where did my - sign go

#

thanks ๐Ÿ˜„

somber nacelle
#

just use Mathf.Abs and you don't need to check against both

gleaming vessel
cinder fractal
#

hi i have a script and a shader that makes my gameobject highlight when needed but when i turn on the shader all gameobjects with this shader material highlight how do i make it so i can choose which gameobjects highlight with one material?

leaden solstice
cinder fractal
hollow fjord
#

anyone know if it is possible to set these values via script?

delicate zinc
#

Given a bounds struct, how could i use said bound's values to check if a collider is inside it?

leaden ice
delicate zinc
#

or just bounds.size?

leaden ice
delicate zinc
#

guh

leaden ice
#

I'll leave that as an exercise for you to figure out because I'm not at my computer

#

Shouldn't be hard to figure out

#

Just read the docs

delicate zinc
#

fair enough i guess lol

leaden ice
#

Sorry to make you actually do a little work? ๐Ÿ˜

delicate zinc
#

its not that, sorry i came out as rude

#

i wouldnt be here if i didnt check the documentation

#

or online

#

i couldnt find a good way to use the bounds struct for an overlap box

#

just a bit frustrated, sorry

scarlet viper
#

Can I somehow create a speed variable for **Vector3.MoveTowards **with Mathf.SmoothStep instead of Vector3.Distance?
Is there a mathematical Trick that could do this?

        float distance = Vector3.Distance(ring.localPosition, new Vector3(0f, targetLocal.y < average ? from : to, 0f));

        ring.localPosition = targetLocal.y > ring.localPosition.y
            ? targetLocal
            : Vector3.MoveTowards(ring.localPosition, targetLocal, 3f * distance * Time.deltaTime);

Distance works fine but its too irregular (too fast at first and too slow at the end)

SmoothStep is mostly the same speed with slower ends, so a preferable solution
But SmoothStep gives value in range between 2 values, lets say between 0 and 1
Im not sure how to create speed out of it.

delicate zinc
#

Ok so, i'm working on a dungeon generation system for my thesis, it's been painful so far (as any procedural generation system). but i've found myself with an issue i dont precisely know how to deal with.)

My system is currently following the idea of using prefabs, the prefab hierarchy has at it's root aRoom component. this Room component contains mainly 2 things:
1.- An array of Door components, to know the entryways to the room
2.- A Bounds struct, which is calculated from the child colliders.

My main issue right now has to do with rotating an instantiated Room so it has the "correct" orientation. On the picture below there are two rooms, the first room (the taller bounding box) and the second room (the one that's shaped as a plus). it may not look like it but the rightmost door is the connection between both rooms i'm trying to make. i know i can use transform.RotateAround on the Room's transform, using the Door's position as the pivot. the issue is, i have no ideda how to properly calculate the angle needed so the room goes from the first picture, to the second picture.

leaden solstice
#

Or consider SmoothDamp?

halcyon venture
#

can someone help me, i have a sprite for a wood plank (2d game), and i want to resize it to be the floor of my game, however i dont want to stretch it out, i want to repeat it until its the correct size, the first image is the one that i want to change to be repeated to make it look like the second image

scarlet viper
#

thanks a lot man

deep oyster
#

Is it possible to get a list of all currently pressed buttons?

heady iris
#

as in, buttons on the keyboard?

#

not UI buttons

deep oyster
#

I'd like to print out a list of buttons the user is currently pressing on their keyboard in a debug window

heady iris
#

I don't think you can ask for buttons that are being actively pressed. You could, however, iterate over all of the KeyCode enum values

deep oyster
#

Ooooh

heady iris
#
        foreach (KeyCode code in Enum.GetValues(typeof(KeyCode)))
        {

        }
#

Enum is from the System namespace

#

note that you have to write KeyCode, not just var or something

deep oyster
#

Can I toString the keycode value?

#

so I can print "Shift" or whatever

heady iris
#
        System.Enum.GetName(typeof(KeyCode), KeyCode.A);
#

ToString might also work

deep oyster
#

Thanks!

heady iris
#

huh, GetValues returns...Array

#

never knew that

deep oyster
heady iris
#

this will generate some garbage, since it's making an array every time

#

but that's probably a non-issue for showing some text in a debug menu

deep oyster
#

hm

#

guess just put var values = Enum.GetValues and then foreach in values?

heady iris
#

You could calculate it once and just keep it, yeah

heady iris
#

it's a really minor thing

deep oyster
#

oh make it a class thing then

heady iris
#

but I guess it would be nice to do something like:

private List<KeyCode> keyCodes = new();

void Awake() {
  foreach (KeyCode code in System.Enum.GetValues(typeof(KeyCode)))
    keyCodes.Add(code);
 }
deep oyster
#

do editor windows call awake when they first appear

#

also is there a controller input equivalent of keycodes

#

buttoncodes or smth

delicate zinc
#

god i feel like i'm going insane with this dungeongen stuff GOINSANE

heady iris
#

You're using the old input system, I presume?

#

If you're using the new one, then you could just iterate over every map in your input action asset, then iterate over every action in every map

deep oyster
#

I don't have any input system right now I'm just messing around with debug windows

#

so now I can see every keyboard input I'm getting and I wondered if I could do the same with a gamepad

heady iris
#

the old input system uses stuff like Input.GetKeyDown

#

so that's what you're using

deep oyster
#

Oh, yeah

#

GetKey tho cause I don't want it to just last one frame

hoary mason
#

I don't quite get this, why does the box's position still go to into decimals?

#
    private void FixedUpdate()
    {
        Hit = Physics2D.Raycast((Vector2)transform.position, Movement, 0.5f, LayerMask.GetMask("Object"));
        if (Hit)
        {
            Stop(Hit.collider.gameObject);
        }
        if (Moving)
        {
            Control.MovePosition((Vector2)transform.position + Movement * spe * Time.deltaTime);
        }
    }
    private void Stop(GameObject collision)
    {
        Moving = false;
        Movement = new Vector2(0.0f, 0.0f);
            if (Mathf.Abs(collision.transform.position.x - transform.position.x) <= Movement.x)
            {
                transform.position = new Vector2((int)collision.transform.position.x - (int)Movement.x,transform.position.y);
            }
            else if(Mathf.Abs(collision.transform.position.y - transform.position.y) <= Movement.y)
            {
                transform.position = new Vector2((int)transform.position.x, collision.transform.position.y - (int)Movement.y);

            }
    }
}
#

the gameobjects it's colliding with's positions are on integers

heady iris
#

is this an object with a Rigidbody2D on it?

#

if so, it will still have a velocity and drift off after getting reposiitoned

hoary mason
#

Either way, fixed it anyway by just changing the conditionals to "if Movement x ==0" for one and movement y for the otehr

#

Seems like it wasn't reading the conditionals well

mortal thistle
#

Hi, does anyone know a good library to decode gif files at runtime ? I would like to be able to download one from a server and use it as a texture, or in a RawImage

ivory crescent
#

Has anyone implemented custom richtext tags in TMP? I cant find anything usefull in my search and just want to know if someone here has done it or has resources to it.

swift falcon
#

Hi, some questions about compute shader
I have a list of vertices that form a 2D loop and I want to iteratively relax the loop like this

  1. Calculate the displacement of every vertex based on the coord of its previous and next vertex
  2. Apply the displacement to every vertex
  3. Repeat 1 and 2 for a certain number of iterations
    I'm wondering if this is something achievable with a computer shader, I'm mostly confused about how to do multiple iterations of the displacement process in a shader
#

something like this:

void Relaxation(int iter){
    borderPos and forces are Vector2 arrays with equal but undetermined lengths
    int loopCount = borderPos.Count;
    for (int iter = 0; iter < 100; iter++){
        for (int i = 0; i < loopCount; i++){
            forces[i] = calculations with borderPos[i], borderPos[i-1] and borderPos[i+1];
        }
        for (int i = 0; i < loopCount; i++){
            borderPos[i] += forces[i];
        }
    }
}
cosmic rain
#

Now, I don't know what kind of calc you need to do, but from the pseudocode it's implied that the calculations are in sequence, so each on would depend on the previous one.

#

Then, there's the issue with the iterations. You'd need to make several dispatches for each iteration, which is probably gonna introduce quite a lot of overhead.
Perhaps with command buffers you can just run each iteration in sequence without getting the data back to the CPU, but that's pretty advanced and I'm not sure if that's possible.

#

I don't know how fast you need it to be, but maybe try implementing it as a job first and see if it's good enough.

mystic fox
#

Hi, I'm trying to move the game to another Monitor I'm using Display.displays[displayIdx].Activate(); and it doesn't seem to work... What I'm doing wrong?

heady verge
#

need Help with

    public void OnMouseEnter()
    {
        if(MDebug)
        {
            Debug.Log("<color=yellow><b> SelectCollider Maus angekommen on Enter </b></color>");
        }
        PlayerFoundDa = true;

    }

Collider = Trigger,
Event System is here,
but if i enter with my mouse, nothing is happaning.
Any Idea ?
( Collider is insde the Hips of a Charakter, do select him ).

#

the Collider is just a simple Cube, downscaled, with a trigger collider.
Do not work.

somber maple
#

something went wrong with building, I really need help

knotty sun
somber maple
knotty sun
#

in that case look in the editor logs
!logs

tawny elkBOT
#
๐Ÿ“ Logs

Documentation
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

knotty sun
#

also what does the stack trace show you when you select the error?

#

chances are you have Editor code being included in your build

somber maple
#

sorrry man, i just had to restart unity.

dusk apex
#

Graphics raycaster on canvas and physics raycasters on the camera - any that are applicable.

mellow sigil
#

Follow the tutorial better
If you need help, post a link to the tutorial, the errors you're getting and the code properly: !code ๐Ÿ‘‡ (the screenshot is unreadable)

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

polar umbra
# mellow sigil Follow the tutorial better If you need help, post a link to the tutorial, the er...

This was the tutorial I was watching https://youtu.be/b0AQg5ZTpac?si=JCFTYY3RY3Hc0t_V

Isometric Mouse Movement in Unity Tutorial using the NEW input system.

๐Ÿ“ฅ Get the Source Code ๐Ÿ“ฅ
https://www.patreon.com/posts/isometric-mouse-38744509

๐Ÿ”— Relevant Video Links ๐Ÿ”—
แ…Making an Isometric Tilemap with Elevations and Colliders in UNITY
https://youtu.be/_TY0F7Zm6Lc

๐Ÿค Support Me ๐Ÿค
Patreon: https://www.patreon.com/samyg
Donate: https://ko...

โ–ถ Play video
knotty sun
#

one for @naive swallow

polar umbra
knotty sun
#

OMG. What she is typing at that moment

polar umbra
knotty sun
#

no

#

mb 11:20

polar umbra
# knotty sun mb 11:20

got that too Vector3.MoveTowards(transform.position, destination, movementSpeed * Time.deltaTime);

knotty sun
#

look again, this time carefully

polar umbra
#

Wow I can't believe I missed that

scarlet viper
#

I noticed people often treat magnitude as speed is this correct?

if (rigidbody.velocity.magnitude > maxSpeed)

wouldnt local velocity's Z be more accurate?

dusk apex
#

The magnitude would be the range of the vector. Sort of like the hypotenuse of some x and y coordinate.

#

Speed and velocity being the same, it would just evaluate the three component float value into a single usable value

cosmic rain
real anvil
#

Magnitude can be considered speed in this case

#

As you don't care about direction

#

(also use square magnitude to avoid an unnecessary sqrt operation)

dusk apex
#

Make sure to square your max speed value, if so.

cold egret
#
  • I'm working with audio source and need to detect the moment when the clip comes to an end, even after being paused, modified by pitch/effect/time etc.. It's been quite a challenge but luckily audio source has a .time property and its compression-agnostic counterpart, .timeSamples, which can be compared to those of the clip. So far it has been working good, but recently i figured out that not always the end is registered. It turns out that sometimes the source's .time and .timeSamples will become 0 without reaching the values of .clip.length and .clip.samples respectively, thus never metting the equality condition in my code. Why is it and how should i work around this?
#
  • An example that i currently have catched:
    .clip.samples - 65664
    .timeSamples in the previous frame - 64915
    .timeSamples in this frame - 0

  • Hence the line under if (_source.timeSamples >= _source.clip.samples) is never executed (in this particular case)

leaden ice
radiant shadow
#

guys, why is null is not recommended using with unity objects? there is a reason?

proud hare
#

That is for GameObjects only right? Things dervied from MonoBehaviour still need "== null" to check?

leaden ice
#

it's not for GameObjects

#

it's for EVERYTHING that derives from UnityEngine.Object

#

including MonoBehaviours, ScriptableObjects, all Unity asset types, etc..

proud hare
#

Oh weird, I got an error the other day because I had
if( myComponent ) {
blah blah
}

And I got an error saying that myComponent couldn't be compared as a bool or something like that. Maybe I misread the error.

#

(I'm just testing it right now...)

heady iris
#

then myComponent's type was not derived from UnityEngine.Object

leaden ice
#

you probably misinterpreted the error

heady iris
gleaming vessel
proud hare
#

..yeh I just tested it, and just as you said ,it works without the ==null

I thought it was odd when I got the error, but I must have been mistaken about what I reading. Probably wasn't a MonoBehaviour class or something like that.

gleaming vessel
knotty sun
#

do you have a jslib?

gleaming vessel
knotty sun
#

there you go, what do you think you are talking to?

thick socket
#
public class Fighter : MonoBehaviour
{
    protected virtual void Awake()
    {
        // Base class Awake logic here
        Debug.Log("0");
    }
}
public class Enemy : Fighter
{
    protected override void Awake()
    {
        base.Awake(); // Call the base class's Awake method
        // Additional logic for Enemy
        Debug.Log("1");
    }
}
public class Enemy2 : Enemy
{
    protected override void Awake()
    {
        base.Awake(); // Call the base class's Awake method (from Enemy)
        // Additional logic for Enemy2
        Debug.Log("2");
    }
}
#

would Enemy2 Debug 0 1 2

#

or just 0 2

#

not sure if it will take Enemy base also or just Fighter base

knotty sun
#

should be 0,1,2

thick socket
knotty sun
#

you could build in a type check in Enemy Awake

thick socket
knotty sun
#

after base.Awake in Enemy
if (this is Enemy2) return

thick socket
knotty sun
#

no, not really, it's checking which class it actually is

thick socket
#

didn't see that coming

knotty sun
#

yes

thick socket
#

so if I had just
if (this is Enemy) do xyz

#

that wouldn't execute as Enemy2 right

knotty sun
#

yes

thick socket
#

๐Ÿ˜„

knotty sun
thick socket
#

gotcha

proud hare
#

If my priority was readablity and not performance. I might go with a generic enemy, and then put extra components on for the ways in which the enemies differ.

So, if I have a generic enemy, and an enemy that makes a beep noise. I'd just add a MakeABeepingNoise component onto the generic enemy.

As I said though, that's not prioritising performance ( or memory usage ) but in some situations ( such as wanting game designers to assemble these different enemies within the Unity Editor ) then it can have benefits.

thick socket
#

however a different type of enemy has a "Monster" script

#

so I need some way to switch things up without also breaking my state machine that uses Enemy ๐Ÿ˜„

knotty sun
#

@thick socket if you want to catch all classes that derive from Enemy you could do

if (this.GetType().baseType == typeof(Enemy)) ...
proud hare
# thick socket gotcha, my main enemy using a "Character" script

There's also a pattern where you can have a StateMachine.cs. , that defines the state machine itself, like the names of states and what can transition to what.

And then you can put the conditional checks, and the actions themselves in another component, on the same GameObject.

Again, you'd need a specific use case for this to be a good solution, and you'd need to be sure your performance wasn't going to suffer as a result. But it can be an interesting pattern because you can even then reuses StateMachines across entities, but the behaviours are further specialised by the additional component.

mellow zinc
#
    {
        if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.3f))
        {
            float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
            return angle < maxSlopeAngle && angle != 0;
        }
    }``` why doesnt this work
#

it says that not all code paths return a value

knotty sun
#

exactly, you do not have a return if the if fails

proud hare
#

just add return false before the last }

mellow zinc
#

what

#

Oh

#

okay

#

thanks

proud hare
#

Also, what do you think of:
return (angle < maxSlopeAngle) && (angle != 0);

I know you know what the line meant anway, but what if someone else less experienced sees it, or you from the future see it when you are feeling sleepy ๐Ÿ™‚

knotty sun
#

actually I think that is wrong is should be a single &

thick socket
proud hare
#

No should be &&

#

but you need != 0f right?
Or can you just use 0 without the f?

thick socket
knotty sun
#

you only need the f when decimals are specified to differentiate from a double

proud hare
#

If you use a single & then it will do a logical AND on every bit in the representation, but seing as it is a float, I think that would be essentially meaningless.

Actually, maybe Unity will stop you from even using & with a float?

knotty sun
proud hare
simple spire
#

Hello guys, I have a navmesh with agents on a 2D tilemap. Everythings fine, but when I want to add a nav mesh obstacle to my agents, they falls like if there was a x80 gravity :/ do you know why ?

heady iris
#

wouldn't that mean the agent is being pushed away from itself?

#

if it has an obstacle on itself

simple spire
#

that was I thinked yes, but how can I do for counting my agent like an obstacle on my navmesh ?

gleaming vessel
#

here is a code

swift falcon
simple spire
heady iris
#

What are you trying to do?

knotty sun
simple spire
#

having agent who avoid others agents in theyre paths

swift falcon
heady iris
#

agents can already avoid bumping into each other

swift falcon
#

If the first one is false, the whole thing will be false, no matter what the second condition is @knotty sun

#

so no need to check both

knotty sun
#

so he wants to know if it is < a figure and != 0. a && will stop if the < is true

simple spire
#

I will try to search why

heady iris
#

it will stop if the left hand side is false, not true

#

and since a != 0 has no side effects, it never matters whether you short-circuit or not

knotty sun
#

true, mb

gleaming vessel
knotty sun
thick socket
#

Why can't I put my Monster Script inside the "Monster" Enemy Character Script

#

and also why can't I enable/disable the Monster Script?

heady iris
#

Second question: if you don't have Awake/Start/Update/etc. methods, you won't get a checkbox

#

because disabling the behaviour would do literally nothing

thick socket
# heady iris Second question: if you don't have Awake/Start/Update/etc. methods, you won't ge...
public class Monster : MonoBehaviour
    {
        public SpriteRenderer Head;
        public List<Sprite> HeadSprites;
        public Animator Animator;
        public bool Variations;
        public event Action<string> OnEvent = eventName => { };
        
        /// <summary>
        /// Called on Awake.
        /// </summary>
        public void Awake()
        {
            if (Variations)
            {
                var variations = GetComponents<MonsterVariation>();
                var random = UnityEngine.Random.Range(0, variations.Length + 1);

                if (random > 0)
                {
                    variations[random - 1].Apply();
                }
            }```
#

when I try to drag it in it gives me the little "icon" that means "sure you can put that here" but then it just doesn't let me

#

(hoping its just a unity bug so restarting Unity rn)
still bugged after restart

heady iris
#

perhaps you have two scripts named Monster?

#

Recent versions of Unity allow you to have a script whose name doesn't match the class name

somber nacelle
#

note that Awake is not affected by the enabled state of the monobehaviour itself but rather the active state of the gameobject. so the checkbox does not appear for just that method

heady iris
#

I just checked; it does appear

somber nacelle
#

what version are you on? because newer versions have the checkbox no matter what

heady iris
#

oh wait, wrong.

heady iris
#

I got punked by saving at the wrong moment. you are correct.

#

Good to know that! I actually didn't know it ignored the enabled state.

thick socket
#

Every script I've wrote has a checkbox and works nicely

#

this is from an asset...however shouldn't change that working imo