#archived-code-general
1 messages ยท Page 195 of 1
"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
i didn't know that it's YAML
What case are you talking about when you say they're not serializable, there are thousands of serializers
Maybe share the code that you use to serialize it.
That doesn't mean anything
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.
Saving what to a file, what format was it serialized into before you decided to write it?
That's not a format that can be written to disk, that's a type
Serializing means converting the data into a format that can be saved to a file. Whether it's binary or text. There are many ways to do it. Just saying "saving to a file" means nothing.
how were you trying to serialize it? Share code.
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.
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide obligatory
Share the latest code that you have problems with and we'll go from there.
yes I know it is not good for security, the compiler literally warns you of that.
I don't even need it anymore. This is not a "help me with my code" question.
this is a "how is it done" question
Well, then we can't answer your question, because it seems to be specific to your use case.
You pass it through a sensible serializer like Newtonsoft.Json, and write it to disk
They want to know how it's done in a SerializableObject I guess...
In the case of Newtonsoft you also need converters because of the way the type is structured, and I posted those earlier
The simple answer would be: Vector2 is serializable by json and yaml by default, so it can be saved as part of an SO.
Well, as that's editor-only and is written in C++ there's no answer that can be given
The YAML serializer reads the data, formats it, and writes it to disk. Just as any serializer does. Is there an actual question here?
I guess not knowing how something is serialized and asking how its done is not a question
Well you've been answered then, many times
@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
I wasn't trying to serialize it to json, I was just asking how it's serialized when it's not marked as serializable. I guess the confusion came from me saying "to a file", because I knew they were serializable because they have to be to appear in the inspector.
So the question is why are they not marked as serializable?
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.
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?
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.
Tbf, you were immediately flat out refusing everything we were saying. I felt hostility from you first.
BUT, I will apologize, because I did make a sarcastic joke and that wasn't fair. I don't mean to turn you off from learning
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...
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
"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
Is it or is it not marked?
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.
Looking at the source code now, I realize that it is not marked.
Something new to learn.
So if you said something and someone who knows more than you said you're "clearly" wrong when you are not even that wrong, how would that make you feel as a beginner?
I guess if an appropriate proof was provided early on, it would've solved a lot of the issues in the conversation.
like they are helping and I need it ๐
You will take a little "abuse" at first
There might've been an issue with my response. I admit. But it all would've been way simpler if there was actual code provided.
builds character
but dlich is pretty great and has helped me out a bunch for sure lol
Right!
I haven't followed convo at all
but Sasquatch B Studios seems up to date and has great info imo
worth watching some/all of his vids ๐
Cool
spent today redoing all my player and enemy AI to make it scriptable objects and my work will be so much faster now lol
Posting something without context that is wrong, and doubling down in the face of others is a fast way to make people annoyed
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.
"Who said they're not?"
"Serialize how? There are many ways to do it."
"https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters"
"The certainly are. Saving a position vector is one of the first things someone would want to save
"My player was HERE when they left""
These are ALL polite versions of that imo.
I'm truly sorry if it came off differently though
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.
Tldr: always post code
There's nothing to learn, the attribute doesn't do anything functionally, it's entirely up to the serializer to care about it at all
It's water under the bridge
I hope so. I DO feel bad. I was trying to just give an example of serializing a Vector
It was just a lot of communication mishaps
I mean, the fact that it was not marked is something new for me.
No one's fault
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.
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
Using dictionaries?
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 ๐
You can literally take an instance of a class, and save one of it's fields to a text file and that would be considered serialization + saving:
class A
{
public int fieldToSerialize;
}
class MySerializer
{
void SerializeA(A a)
{
File.WriteAllText(path, a.fieldToSerialize);
}
//Deserialize - overwrite or create a new instance and read the value from a file
}
There are lots of tutorials on YouTube on how to make serializable dictionaries
If you use a third party json library they will tend to be able to serialize dictionaries with no work
all I need to store are int bool and float so I'll probably figure things out
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?
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
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?
dont cross post, do you know what is array? btw if you have multiple switchunit then you have to change the second if statement
what exactly do I write?
I know a bit about arrays but not enough to do this apparantly
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);
}
}```
I tried doing this, it didn't work.
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
you should go through the basic c# courses pinned in #๐ปโcode-beginner to learn how variables and collections work
Can you explain in more detail what you mean?
Do you want an array that contains all SwitchUnit gameobjects in the scene?
I also agree with boxfriend that it might be good to watch a quick tutorial on variables and arrays in C#
what are you trying to do? because the code you posted before is almost nonsensical in what it does
Basically, this code works. But the problem is that I have to assign SwitchUnit from the inspector.
Instead of doing that, I was thinking of making an array and adding every single Unit in my game into the array(which are all gonna be considered SwitchUnit in my inspector)
It's a card game mechanic where your card(A) can switch positions with any other card(B) that is adjacent to (A).
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
something like this
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?
ClassB should expose an event Action<float> instead
Then ClassA can subscribe to it
what SPR2 said, but also delegates are immutable. every time you += it, it creates a new instance of the delegate. like how strings work
Then I guess your RegisterAction method could take a ClassB parameter, and subscribe to the event
I see... so it's not possible doing that way...
Seems like this is a good alternative, I'll try this instead, thanks
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
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?
you need to be more specific about what exactly is not working. also #archived-networking
oh okay thanks
event handler cant do the job? using eventArg
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
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
I figured it out
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
is there anyone that can make a unity game with me
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
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
A) This is a Code only channel
B) Don't cross post
no hlep
I saw your question there and I didn't understand it. Rather than referencing a game people may not know, describe the behaviour you want.
Aging can just be a number you increment after a timer completes. Use coroutines?
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?
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
if you use an enum with the Flags attribute you can have multiple states at one time
@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.
(Using the old input system btw)
true, each state would need logic to behave appropriately depending on the combined state
i.e. Jumping, Crouching and Attacking
I don't think attacking should be a state. I also wouldn't make jumping a state. I would make walking and falling states. You can attack on both states. You can jump when walking, which changes state to falling, and you might be able to double jump when falling (if that's a thing in your game)
@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
I don't think you'd need to keep track of the state within the attack. Instead you could make so that states that should cancel the attack do that when entering the state, if is attacking
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)
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
Yeah, sorting by name is ok, this one I get. Looks like it loads up too much unnecessary suggestions - I don't know why
I've opened older project in VS2019 and it shows me only those suggestions that I need.
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
That was exactly that, thank you sir ๐
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 ๐ค
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
It's comparing a layer and a layer mask. They're different things.
Try if((whatIsWall & (1 << collision.gameObject.layer)) != 0)
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...
there is this https://docs.unity3d.com/ScriptReference/LayerMask.GetMask.html
Mask from name(s)
Right, but this is about getting a mask from a layer ID
I guess you could go ID -> name -> mask
then you bitshift
ye
I just find it to be unintuitive to look at, compared to everywhere else that you use named methods on LayerMask
easy way to solve, make a struct for all 3 values
what did you say
make a reference to your inventory component in your pickup weapons script
you should really !learn the basics
๐งโ๐ซ 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/
There you go
https://pastebin.com/8sewQ28y
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?
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?
Do you have an custom editor in the one but not the other?
Button.interactable to make them unclickable. For moving them around a tweening library like LeanTween is nice
Hello, i have trouble i'm trying to do a save system, for the file it seems to work pretty well, but i can't manage to get a hold on my variable to save the right stuff in the file --> https://paste.ofcode.org/EJXi3ibSB59dPnGnLNkgCJ
Looks like you're trying to save the whole PlayerMovement component
unfortunately that doesn't work
you are declaring and instancing Savedata but you never fill it with anything
Sadly i can't get a touch in it's properties somehow
Wdym?
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
What properties do you need?
Just do player.PROPERTY = ..
(provided they're public, but you could just make the public if not)
When i set public it break the thing, some are in private
To be sure the code for the file itself is good ?
no
What's stopping you from making the properties public?
Error
What error
sec i'm on my phone
What's the problem ?
data will always be as good as empty, so what's the point of saving it
They're probably mutating it from somewhere else
SOLID
I have PlayerMovement file somewhere, which has data i wanna keep
post playermovement script
It's kinda huge though, it' a mess even i don't want to read it
What do you want to save?
we can't help you with it if we cant see it
that's the important part
Like coin or Health or player position
Friend made it like that, don't ask why he didn't split in other files
[System.Serializable]
public class SaveData
{
public int coin;
public float health;
public Vector3 position;
}
```You have to pull them out manually and apply them in `Load()`
You should be able to set playerHealth to be public
Ok, it's a Monobehaviour, you cannot serialize that
How can i fix that ?
I don't manage to pull them, even as public
Show how
make another class and copy the variables from PlayerMoveMeny to that class then use that class in your SaveData
You have to get a reference to a PlayerMovement component, not just use the class name
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
Mh, it break in an another file
doubt
GetComponent<PlayerMovement>().nbCoin += qg.quest.gold; was this one
that is public
Then i'm doing it wrong
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?
Nah it made the error when i put nbCoin as public static
cannot be static
That the only way i found to pull it out, but it didn't work anyway
why would you even think of making it static?
this GetComponent<PlayerMovement>().nbCoin is how you pull it out
No i tried it and not working either
did you do the GetComponent on the correct gameObject?
seems to me like you need a lot of !learn
๐งโ๐ซ 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/
Probably, yes i don't say i'm good, i'm trying to improve also
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.
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 ?
Application.persistentDataPath
Be sure to also use Path.Combine when making paths to make it compatible with every os
Fantastic, this is exactly what I was looking for, than you so much @sage latch !
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.
You have to get a reference to the PlayerMovement component, but it's on another gameobject
easy way is to make a public field of type PlayerMovement in the SaveSystem
then you can drag the player in
public PlayerMovement player = new PlayerMovement(); wasn't this meant to do this somehow ?
You shouldn't create new components with new. Plus, you need the PlayerMovement that is attached to the player
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)
Yes i checked the JSON only getting ID
Yeah
does someone know how to remove those 2 <No Name> file templates?
SaveData doesn't know of player
put that code in Save() instead
why there is public class called SaveData?
To put data i want to store in
ok i see now what you are doing , saving coins amount that is in the playerMovment class right?
Yes
Putting PlayerMovement Player in Save() break everything
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
Resources.Load asks for folder name but how do I load a file with a specific name?
Ah
Give it the path without the file extension
How would it help
you just type folder and name right? one sec let me check
So folderName/fileName?
It asks for a path. The end of the path is the specific file name
Yes
yeah
@sage latch Ok seems to work
Resources.Load<FileType>("Folder/fileName");
Dosc tho: Pathname of the target folder.
Got the coin saved on the json
??
if target in Resources folder without sub folder you just type file name
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
I think it's specifically for loading a whole batch of stuff
Different method. As they said and you know, so just reiterating
The description says Asynchronously loads an asset stored at path in a Resources folder. so I guess they're a bit indecisive
So i just gotta do for Load(), player.nbCoin = data.coin; right ?
async load with task so you dont have to wait for the load to finish unlike normal load
Yeah
After you load the data
Alright, thanks Bobbo !
Bobbo!
My Load is in an another scene how can i retrieve my Player GameObject ?
That's a harder task
Harder but possible ?
Do you have to get the save data in the other scene?
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
But the button for Loading is in the menu though
So the button for changing Scene, and Awake that load data
Yeah
Okay ! Thanks
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
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.
oops, hit enter early
Also I just answered my own question while typing it out. So, all good ( :
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?
How do I load a json file in the projectโs build? ie how do I target it via path?
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.
Use a Text asset.
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
That method creates the file if none exists.
How do I check if a collided object's layer is contained within a layermask?
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.
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;
}
}```
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 ?
You can only use constants as switch cases unless you're doing pattern matching
So do I just resort to nested ifs?
or rather else if
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
You should be able to simply subtract gravity from player velocity in Update().
playerVelocity -= gravity * Time.deltaTime
Is there a similar thing for when creating a bunch of objects? So that I can cancel them all with a single Undo
Else if chain or a switch with pattern matching syntax https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching#multiple-inputs
thanks ill look into it
Undos tend to automatically collapse if you do things at once
Which one would be suitable for recovering a deleted object?
But in this way, when player stand on slope, the gravity will keep pull player down slope.
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
you mean set gravity to zero when grounding, so it won't keep subtracting velocity?
are you working with slopes and a dynamic rigidbody?
kinematic
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
yes, so I need to code gravity by myself.
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
Thank you for your answer, I will try it
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)
Look into converting int to an enum
Enum aren't indexes
They're just int
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
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
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.
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
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?
dont crosspost please
You have not set up your gitignore, the Library folder should not be in your commits
!vc
โข PlasticSCM
โข Git: Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory
okay, how can I add this to my code?
Okay, thank you!
Any idea on this? ๐
No idea but why would you want them to fire in edit mode
I'm implementing subtitles so that it'd be easy to tweak them in edit mode
I found a better solution though, making them with timeline tracks instead of signals
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
Can you StartCoroutine it instead of calling it
I know you can yield startcoroutines, maybe thats whats happening here
Yeah just guessing, but maybe StartCoroutine(base.Collide(collision, expectedPos))
You might end up with two simultaneous coroutines tho
I think that's the intended effect
So as frant said, yielding the base coroutine first might work
I assume by interrupted he means the coroutine stops for the base coroutine to be called
It probably doesn't "stop", it just never gets properly started
Right, interrupted is pretty unclear here
Anyhow, startcoroutine is the first thing no matter what
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
Who's calling Collide to begin with?
a player
How?
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);
oh, yeah, exactly!
I haven't mentioned it
thank you!
๐
now it works, what a stupid mistake of mine
Hehe it happens
Looking at your code snippets, there's nothing that requires them to be coroutines though. You sure you need them?
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
yes, I'm gonna implement further logic right now
Alrighty
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>?
You can cast it
For example
(Potion)GetComponent<Item>()
or
GetComponent<Item>() as Potion
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
Oh wait no that still wouldn't work
var stick = (Stick)GetComponent<Item>()```
Component component = itemHolders[val].GetComponent<InventoryItem>();
Destroy(component);```
What're you trying to do specifically?
Essentially trying to destroy any components of the Item class
What do you think are the "components of the Item class"?
Oh sorry of the InventoryItem class
Same question
Any script inheriting from it
Then your script basically should already work
It's not seeming to destroy it though so I feel like I'm goofin up somewhere
If Potion inherits from InventoryItem, and you find all components of type InventoryItem, it should return Potion as well
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
Heheh
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?
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
that's a good point, although i imagine that's still equally or less expensive than if it ran every frame too
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
yeah i'm far from having them as issues, just was curious if that's something people use them for or not
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...)
whats wrong?
Maybe .SetBool("IsJumping", true)
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
are you sure this is the code that causes the issue?
yes, if I return; at the beginning of the code, it doesn't spawn objects and game isn't broken
I have just tried to spawn just 1-4 items and unity didn't seem to broke
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
but it can't be because of performance issues?
no, that wouldn't cause unity to completely lock up forever. that would just cause things like reduced frame rate
I see, is there any wait just to pause the game when it breaks?
use breakpoints
in order not to restart unity every time
I have used them already, I haven't mentioned anything strange
use them to pause execution. you know, to stop your infinite loop
but I don't know where my infinite loop is..
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
I have asked if there's any way to prevent unity from breaking without using any breakpoints
guess no then
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)
I see, I'll try to find them, thank you ๐
I dont think so?
but if you plan to run that in Update, then yes?
you need MonoBehaviour to have Update
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
You just need access to the Time class but this only works if used every frame, hence you'll need a MonoBehaviour class that runs this code for you in their Update . . .
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.
yeah...however the class itself doesn't need to be a MonoBehavior as long as the time method is being used by a class inside of a MonoBehavior's Update right
Either get a Dictionary<FacingDirection, Vector2> and fill it manually, or make a utility method that converts the enum to a vector. Extension method is also possible!
// In STATIC class
public static Vector2 AsVector2(this FacingDirection dir) => dir switch
{
FacingDirection.North => Vector2.up,
// etc.
}
Usage:
Vector2 v = FacingDirection.North.AsVector2();
Yep. You can use UnityEngine code in regular c# as long as you have the correct using directive . . .
I'd do this:
public static class FacingDirectionExtensions {
static Dictionary<FacingDirection, Vector2> dirMap = new() {
{FacingDirection.North, Vector2.up},
{FacingDirection.NorthEast, (Vector2.up + Vector2.right).normalized},
// etc...
}
public static Vector2 ToDir(this FacingDirection dir) {
return dirMap[dir];
}
}```
ah sorry i was slow
very similar to SPR2's
Mix of both, not sure which is more performant
they're probably similar. I think the switch becomes a jump table at some point
Yeah it has 8 cases so probably becomes a jump table
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?
Oh, thank you so much guys! That's very helpful.
becomes a jump table
What does that mean (if you don't mind answering)?
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?
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:
- convert the enum value to a number from 0 to 7 (one per direction)
- use that number to move the execution to [the current line + the number representing the enum value]
- create the vector on the instruction it falls on
- return it
It's like the dictionary, but a low-level representation of it, known when the compiler goes over your C# code
So.. is it like a hashtable?
Yep, but made in the IL code C# compiles to
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;
}
}
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
That's very detailed, thank you for the explanation!
oh thanks!
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)
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
make the routine start from a monobehvaior
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?
I'm gonna be honest, that is stuff I never heard of. So it's a little bit hard for me to understand.
But I guess performance is never an issue in my case, right?
iirc you only need monobehavior to start from a mono, but the IEnumerator can be in a reg class
i tried doing just stateManager.StartCoroutine but got this after
actually this might be unrelated, lemme read some more lol
Yeah in this case you don't need to worry about it. Look for more expensive stuff like repeated Find() and GetComponent<T>() calls in frequently executed code like in Update
whats on line 39
ok yeah nvm fixed it, doing stateManager.StartCoroutine works fine ๐
niice
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;
}
}
Why are you passing in 8 as a layer mask?
That's almost certainly wrong
that is the layer index of the layer they are on
right so it's definitely wrong
because that parameter needs a layer mask
not a layer index
oh! right!
The easiest way to deal with layer masks is:
public LayerMask myMask;```
๐คฆ
define it in the inspector
I did the exact same thing ๐
What you did makes sense to me lol
But Unity says no
Using magic numbers is also frowned on :l
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
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
how can I know if it is local, sorry I am kinda new to this
You'll see it on your computer as a file, using your file explorer
like this?
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
I wonder where your Git root is, then, maybe one folder above?
Based on this image the root is in the fodler that contains the project and some other folder
okay, so move that folder into the FBLA one?
could I just move it
or how it's relevant here
The FBLA folder is where my game is locaed
no your game is located in "My project"
or rather
this might be two different projects
Yeah I think it is in the FBLA folder
yeah this is definitely multiple projects
yeah... so what sould I do?
for simplicity I recommend only having one project per git repository
Now you can pull the whole contents of FBLA onto the git root one folder above
okay
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!
What, no look at the screenshot I posted
so what did I do wrong
You moved the folder into the git folder
Move the contents of FBLA 2023-2024 Unity into Documents/Github/FBLA-2023-2024/
It'll be empty, so yep
The first 5 files indicate you're still in the .git folder
yeah you've really messed something up lol
you shouldn't be poking around inside .git typically
Should be like this ^^^
Project folders along .git
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.
IdleStatein the namespaceMyGame.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
Okay I think I see now
Like this?
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
Okay I finally GIT it now thank you!
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
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 ?
!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.
(small blocks like this just need the inline-code treatment)
Physics2D.IgnoreCollision will ignore collisions between a single pair of colliders
Oh , Is there an alternative ?
I'd put all of the enemies on an Enemy layer, and put the player on a Player layer
then you can use https://docs.unity3d.com/ScriptReference/Physics2D.IgnoreLayerCollision.html to ignore collisions between two entire layers
Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("Enemy"), true);
note that I used LayerMask.NameToLayer, not LayerMask.GetMask. GetMask is not used here.
Oh : Thanks !
note that you will want to look at the Physics 2D settings if you need to turn collisions on or off between layers
Thanks again for your help. Everything is now working as I intended now!
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)
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");
}
}
UI Menu on Unity photo: https://discord-cdn.is-terrible.com/6f29EzbPP
wdym 'can't seem to do it'?
Ohh sorry, i forgot to share the error ๐
Unity prints out this error: https://discord-cdn.is-terrible.com/6f2baGDkv
Side note, you don't need the GetComponent in Start. Your field is already of Button type.
Oh thanks!
Are you sure you dont have 2 UIMenu scripts enabled?
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
clicking the error might take you to the offending object
Yep! That was it. Thanks a lot guys! โค๏ธ
Is there a way to enable/disable a component in a script (not at runtime level but during editor)
it's exactly the same code
Uhh, but monobehaviours only work at runtime, right?
yes, thank you
or [ExecuteAlways], to make it work in prefab mode as well
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 ?
Yes. 1 being equal to the second parameter, and 0 being equal to the first in lerp
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;
}
aka your top code works but the code you just posted doesn't?
the top code doesnt work but the code i posted now does
I don't really understand what you're trying to do in the first snippet
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
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
yeah its pretty nice sometimes, I used to for making 2 enemies track each other to always look at each other in 2d
unity does that great in 3d but its 2d doesn't exist
I find it decent for shader stuff but that's less specific to unity
So far I haven't had a topic where it wouldn't be at least somewhat useful
And always so friendly too
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
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?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What method is called when player exists the game? (also when I exit it in unity using play button)
void OnApplicationQuit()
{
Debug.Log("Application ending after " + Time.time + " seconds");
}
forgot to mention that it doesn't work for me
it doesn't print anything
What platform are you on?
Windows
Are you building to windows?
yes, "Windows, Max, Linux"
actually I have forgot to save changes is VS, OnApplicationQuit works now ๐
thank you ๐
Lol, it happens to everyone. Glad you found your issue!
That's the hardest thing to debug remotely; you've done everything right but you haven't saved your files...
nah I was saying that LookAt in 3d works great but not in 2d ๐
Well... Yeah
more like I would have expected if they had a lookat 3d function they might have one for 2d
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
thats what I was trying to say that I did ๐
Hmm okay ๐ I'm a little lost but no worry
Did you pay respects to me?
(isn't that what F stands for...)
i would not consult a spam machine
what is the matter?
lol
are you having problems with it behaving weirdly when looking at something close to the up-vector?
Why not utilize a tool that provides really good starting points and tips for almost anything you do
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
So do developers
yes, which is why I prefer to not add more spam to my plate
also, see #๐โcode-of-conduct .
and what do you plan to do if the plausible text is just outright wrong but looks correct?
"i learned wrong on purpose!"
asking or answering questions based on unverified AI-generated content is not allowed (for this reason)
You modify it to your needs and use it as if it was entirely written by yourself
Well, I don't think we did either here today
ah so you still use the wrong information. lmao
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
it is a tautology: if you know enough to fix AI-generated spam, you didn't need the AI-generated spam
You're very black and white about the topic
because very often it just produces text that is outright incorrect. and you have to already have experience in the topic you are asking it about to actually spot that
end of story. don't tell someone to "go ask GPT"
Have you even tried to use it to your purposes?
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.
I mean if that topic is not accepted on the server as discussion, then sure I'll shut up
i've tried to FIX a large amount of garbage code
only to be told that, surprise, it's garbage because ChatGPT spewed it out
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
not necessarily, its nice for explaining what code does most of the time, giving and helping correct math functions and telling you which function might do what you want
The code looks plausible, but then it's just nonsense that doesn't do anything
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
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.
just learn to read and search documentation. you'll get what you need.
and how many times was it wrong? or can you not tell when it is wrong because, as you said, you are new to coding?
it is an unending tide of spam and i'm tired of it
Did I say I'm new to coding?
well, you're espousing the gospel of AI spam, so...
usually it's much faster to ask ai, than using a browser (assuming you know how to ask questions correctly)
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
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.
from my experience...its almost always wrong
however it typically gets you close enough to just need a few tweaks
well, of course it won't be great if you just say "write me code to do smth" and copy paste it in your ide
saving me a lot of time when using functions I haven't done much with before
if ya'll wanna go and "ask questions correctly" you can keep that somewhere else. AI generated answers are not permitted here and it's a shit response to just go "go ask chat gpt" in response to someone's question
I don't think anyone said that in response to someone's question
I scrolled up to find it, and in the process of linking it, hawk deleted it lmfao
It said it was good for math
this you #archived-code-general message
neither do I think I have answered or asked questions using ai
I can neither confirm nor deny this ๐
Well yeah but I gave the actual thing to ask. And it was used as an example. I don't think HawkAngel was having any issue, we were just talking about the subject in general
you can set transform.right or transform.up to make a transform face a certain direction
this works correctly in 2D
e.g. transform.right = target.position - transform.position;
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?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
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.
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
calling LogIn from Start also means that the code in Update hasn't run yet, which will mean the text input fields never got read
that seems weird.
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)
"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
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
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!??!
is 0 less than 0.2?
just use Mathf.Abs and you don't need to check against both
I tried using this method but the result is the same. I can't even understand where the error is, from my side or from the site side. How can I check this?
https://docs.unity3d.com/2021.3/Documentation/ScriptReference/Application.ExternalCall.html this apparently is obsolete
They do give this as an alternative https://docs.unity3d.com/2021.3/Documentation/Manual/webgl-interactingwithbrowserscripting.html
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?
Renderer.material is easiest way to copy material. Also you might want to consider batch-able solutions such as MaterialPropertyBlock
Thanks! But if i have 2 materials on a gameobject how do i specify that i want the second one?
Given a bounds struct, how could i use said bound's values to check if a collider is inside it?
thx
Since a bounds is a box you can use Physics.OverlapBox and check if the collider is in it.
hm, idk but i asume i'm supposed to use bounds.Extent for overlap box's half extents?
or just bounds.size?
Use the properties from the bounds to make an equivalent box for overlap box.
guh
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
Sorry to make you actually do a little work? ๐
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
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.
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.
Use something like Lerp(s, e, SmoothStep(0, 1, t))
Or consider SmoothDamp?
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
I think smoothdamp is even better than smoothing at the ends
thanks a lot man
Is it possible to get a list of all currently pressed buttons?
I'd like to print out a list of buttons the user is currently pressing on their keyboard in a debug window
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
Ooooh
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
Thanks!

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
You could calculate it once and just keep it, yeah
just making a local variable wouldn't do anything, since you'd still be computing it every frame
it's a really minor thing
oh make it a class thing then
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);
}
do editor windows call awake when they first appear
also is there a controller input equivalent of keycodes
buttoncodes or smth
yeah, see the "messages" section of the docs https://docs.unity3d.com/ScriptReference/EditorWindow.html
god i feel like i'm going insane with this dungeongen stuff 
not that I'm aware of; you would have to query GetButton for various buttons defined in the Input Manager
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
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
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
is this an object with a Rigidbody2D on it?
if so, it will still have a velocity and drift off after getting reposiitoned
It is kinematic
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
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
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.
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
- Calculate the displacement of every vertex based on the coord of its previous and next vertex
- Apply the displacement to every vertex
- 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];
}
}
}
Shaders are applicable when there's a huge number of data that needs one specific processing applied to each data element in parallel.
If the processing is sequential or dependent on the results of processing for other elements in the collection, shaders wouldn't work.
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.
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?
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.
something went wrong with building, I really need help
Read your error message, fix the compile errors
idk how this works, i double clicked the error and it sent me to an empty script blud
in that case look in the editor logs
!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
also what does the stack trace show you when you select the error?
chances are you have Editor code being included in your build
sorrry man, i just had to restart unity.
Make sure query hit triggers are set https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseEnter.html
You may also need a raycaster component https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/Raycasters.html
Graphics raycaster on canvas and physics raycasters on the camera - any that are applicable.
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)
๐ 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.
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...
So look at 11:32
one for @naive swallow
which lines?
OMG. What she is typing at that moment
yeah my code is exactly the same if (Vector3.Distance (transform.position, destination) > 0.1f)
got that too Vector3.MoveTowards(transform.position, destination, movementSpeed * Time.deltaTime);
look again, this time carefully
Wow I can't believe I missed that
I noticed people often treat magnitude as speed is this correct?
if (rigidbody.velocity.magnitude > maxSpeed)
wouldnt local velocity's Z be more accurate?
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
An object doesn't have to be moving along it's Z axis to have velocity(and consequently speed). It could be moving sideways or any other direction.
Velocity is speed + direction
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)
Make sure to square your max speed value, if so.
- 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
.timeproperty 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.timeand.timeSampleswill become 0 without reaching the values of.clip.lengthand.clip.samplesrespectively, 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
.timeSamplesin the previous frame -64915
.timeSamplesin this frame -0 -
Hence the line under
if (_source.timeSamples >= _source.clip.samples)is never executed (in this particular case)
The audio system runs on a separate thread so it's very likely Update will not coincide with the final audio sample.
guys, why is null is not recommended using with unity objects? there is a reason?
yes, it's because it doesn't respect Unity's overloaded == operator which checks for destroyed objects
That is for GameObjects only right? Things dervied from MonoBehaviour still need "== null" to check?
no
it's not for GameObjects
it's for EVERYTHING that derives from UnityEngine.Object
including MonoBehaviours, ScriptableObjects, all Unity asset types, etc..
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...)
C# is not C++
then myComponent's type was not derived from UnityEngine.Object
There is an implicit conversion to bool operator for UnityEngine.Object as well, so it WILL work assuming myComponent was a MonoBehaviour or something:
https://github.com/Unity-Technologies/UnityCsReference/blob/0e55b91bc34b1d385a5785cd3d9e2246098e2d37/Runtime/Export/Scripting/UnityEngineObject.bindings.cs#L115
you probably misinterpreted the error
(or you had another error)
@primal wind Hi! I tried to make communication with website like it, but now I have error when I want to build webGL project
..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.
so Hello is in your jslib?
I can't even build it to test it on website
do you have a jslib?
no
there you go, what do you think you are talking to?
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
should be 0,1,2
Is there a way to take only Fighters base and not Enemy base as Enemy2?
you could build in a type check in Enemy Awake
like just a bool?
after base.Awake in Enemy
if (this is Enemy2) return
gotcha, I assume thats just setting a protected bool basically?
no, not really, it's checking which class it actually is
oh thats the actual code
didn't see that coming
yes
yes
๐
because Enemy2 is Enemy2, Enemy and Fighter
gotcha
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.
gotcha, my main enemy using a "Character" script
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 ๐
@thick socket if you want to catch all classes that derive from Enemy you could do
if (this.GetType().baseType == typeof(Enemy)) ...
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.
{
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
exactly, you do not have a return if the if fails
just add return false before the last }
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 ๐
actually I think that is wrong is should be a single &
yeah I'll just add 1 extra perameter to my base Fighter that only Monsters use ๐
in if statements you use 2
you only need the f when decimals are specified to differentiate from a double
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?
but not in this case I suspect he wants to always evaluate both conditions hence the single &
Oh, thanks for clarifying that.
interesting
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 ?
wouldn't that mean the agent is being pushed away from itself?
if it has an obstacle on itself
that was I thinked yes, but how can I do for counting my agent like an obstacle on my navmesh ?
Sorry, if I was rude. English is not my native language. I understood that I should have jslib file in Unity and now it works, but I don't understand how to communicate with FronEnd developer to get info about a player with my jslib file
here is a code
Why would he always want to evaluate the second condition?
when I do research on internet or unity manual it was the only solution I saw, but I'm agree with you I think he push himself
What are you trying to do?
becuase he is checking for a < and a !=
having agent who avoid others agents in theyre paths
And?
agents can already avoid bumping into each other
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
so he wants to know if it is < a figure and != 0. a && will stop if the < is true
on my game right now they collapse each others
I will try to search why
No it won't
you have that backwards
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
true, mb
@knotty sun
you just write javascript, you can access anything in the webpage js that happens to be running
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?
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
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
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
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
I just checked; it does appear
what version are you on? because newer versions have the checkbox no matter what
oh wait, wrong.
2022.1.23f1

