#archived-code-general
1 messages · Page 99 of 1
ngl did not know u could do ithis
in c#
knew you could do it in golang just not c# haha
tuples?
return multiple values
in go its like
func test() (bool, string) {
return false, ""
}
ok, that one would need SO but i can almost guarantee you're thinking about it wrong
object/struct/ref/out, many way to return multi values
forgot about ref tbf
they have different semantics so its not strictly return
Just math related more or less: How would I calculate what torque is needed for something to reach a position?
something about differential equations
Newton's second law of motion or sumthin
Here's my paint perfection of what I was trying to do @twin hull
Main Job System holds a list of the JobBase, So any job can be in there.
Then those Jobs have a leveling system attached to them to track exp etc etc etc
Think FF14/11
instead of jobs why not make trainable skills? so they can use all kinds of equipment
This wasn't really going to get implemented into anything, yet. It really was a learning experiment for myself.
ah i see, only reason i say this because old school runescapes combat system is very nice
simple but complex which is what im basing mine off
I was trying to make it so if i ever created another Job it would easily be able to be added to the list. But i guess im going about it wrong code wise
I understand what I want, just dont know how to do it fully.
Other than SO's
I suppose im relying to much on the inspector to fill in data rather than just doing it in code.
SOs are a bit of a nightmare to work with, but for a learning project it might be fine
why not have an enum for job type?
like mutating assets
Isn't that only good if you know how many you want from the start, and only a small amount.
you can add to the enum
example?
But say you remove a class for some reason, then the enum could be out of line.
enums are scary for this reason
yes thats bad
but I think it's also just a Bad Idea
i was getting inconsistent behavior between the editor and the build
yes its a fundamentally bad gimmick
not if you do it correctly
for instance dont just do straight if/else comparisons
i kinda see what you mean like with items and stuff
but if your items derive from 1 base so that has the data just make sure that the enums sync up
it felt clever at first
then it continued to feel clever (derogatory)
i'm now happily using SOs for tons of immutable data
weapon definitions, save points, currencies...
when i first saw that talk few years ago that popularized it, i kinda ran the simulation of what the project would look like in my head
i realized that the maintenance cost of this would be astronomically high on complex projects
the programmers having to dig through editor serialized reference chains
having to debug giant unreadable stacktraces
no validation can save you from design time errors
yes, that is perfect and intended way to use them
the unity editor is telling you that a serialized reference is missing
somewhere
what, you want more information? die
well, that's more of a [SerializeReference] problem :p
they're a great enum replacement, although it does require a little thinking
for example, I replaced my "player stat" enum with scriptable objects
the one problem is that I can no longer just say Stat.Health
however, it turned out that there were very few places that it was reasonable to hard-code that (e.g. checking if you are dead)
Hi, so I want to save & load any replays which are made in the game. the replay mode already works, and there are no issues in the editor. but as soon as I try to save or load in the build game, the game crashes at the point I click. does anybody maybe know the reason? thanks!
btw: this is for my game Unity Flight Simulator with over 4.5k downloads, and It would be very nice, if I can implement that save & load function
so I just gave each entity a list of stats that, if they hit zero, cause death
that sucks
i use a split between editor serialized block and runtime block
i.e. the scriptable holds serialized stats, simple pod with float fields
on runtime the user stat class simply reads it and initializes
so that is not direct hooking of SO as a data ref
there are a few places where this is more beneficial, for example when user class is volatile
i only have to ever edit the init method where the stats are populated with values, but i dont have to keep them in any way synced or coupled
anyway here's the post:https://forum.unity.com/threads/replay-saving-file-working-in-the-editor-but-crashing-in-a-build-game.1433938/#post-8997865
I would really appreciate any help! thanks
private IEnumerator shootAtPlayer()
{
LeftShoot();
yield return new WaitForSeconds(6f);
RightShoot();
yield return new WaitForSeconds(6f);
Debug.Log("coroutine finished shooting");
}
This code makes the left gun shoot a ton of times and then makes both of them shoot a ton. I want the left gun to fire once and then wait 6 seconds, then the right gun fires once and wait 6 seconds. Im still kind of new to using IEunmerators.
and that serialized stat block is a class, so can be embedded anywhere
The code you shared does what you want.
"im starting a coroutine every frame"
If it's firing multiple times you're probably running the coroutine many times
startcoroutine just continues it if its aleady running I thought
No it starts a coroutine every time you call it
StandaloneFileBrowser? the one with a bunch of native libs?
What else would it do
I see it used a lot, I thought it was just the only way to start a coroutine
Evening, is it possible to paste a gameObject inside multiple different parents?
is there a different method
At once
idk, i found that and tried to use it, it works perfectly fine in the editor, but crashes in the build game
guard the start with a bool
It's the only way to start a coroutine
or track existing coroutine
Why would there be another way?
You need to not start coroutine if your previous coroutine unfinish
If you don't want to start another coroutine, don't call it
test if the correct dll is copied for the platform, test on different platforms, test different lib version, see if the dll in unity is correctly setup for target platforms
somewhere there can be a solution
hmm okay
this coroutine is supposed to be used if the player gets in vision of the enemy, 6 seconds is just a ridiculous number for testing purposes. how can I check if the coroutine is running and not start it if it is?
Why don't you just start it when the player enters the range
And stop it when it leaves
It doesn't need to go in update
hed need a while loop there
Definitely think it was Moses
I got it work properly, thanks everyone. I just did something llike this
if (!currentlyShooting)
{
StartCoroutine("shootAtPlayer");
}
dont forget to stop it
also dont use string
just pass the method directly
StartCoroutine(ShootAtPlayer());
Question. Im going to run into a problem if I have the leveling system on the ScriptableObject Job aint I?
what is the difference between the 2
the latter will not let you compile if you screw up the name
got it
leveling system is an actual system or just data?
Suppose its just data at this point
probably a good idea to change the name
yeah, there was no error before crash
now I am trying to use using System.Windows.Forms;
if that doesnt work, then I know that this isnt the issue
that is not gonna work
I could pull it out into its legit own system and make List of this data based on the jobs. idk.
if its just a data object you embed into another its fine
well it worked in the editor again
if by design they are supposed to come together
you are simply abstracting reusable data blocks into classes so you can compose various data objects
what's KeyCode of the button that is called "End" and located at the bottom right corner on the laptop near "PgUp" and "PgDown"?
I doubt it, Windows.Forms is incompatible with Mono or IL2CPP
idk if it will work in the build game
that StandaloneBrowser is a native lib
we will see in a few secs
Unity does have KeyCode documentation for you to refer to
solved. KeyCode.RightArrow
that is...not the end key
so next time, search first, ask later
it is
click on KeyCode, press F12
<- Home
-> End
indeed
maybe if you have one of those small keyboards
that requires a function key to be held to get certain keypresses
Okay, the System.Windows.Forms works, but it looks weired af
ok then
or did you want the right arrow key?
yes, I wanted that "End" key of mine
so i know that StandaloneFileBrowser is the crash issue
but not the end key
good, now I want to get the normal explorer and not that crappy thingy
most keyboards don't overlap the two
yes, I was wondering why this code was not working 🙄
if (Input.GetKeyDown(KeyCode.End)) audioSource.time += secondsRemote.home;
else if (Input.GetKeyDown(KeyCode.Home)) audioSource.time -= secondsRemote.end;
haha
that looks like the ui toolkit unity uses without its unity skinning
big "windows binary from 2005" vibes
isnt there a way to make it look good
i think it is lol
afaik it was gtk 2
?
unity ui is using it
I'm trying to make splash damage in a 2d game, but the projectiles aren't doing damage. I've figured out that it isn't making it to the code in the red square, but I don't know what it is beyond that. However, a problem might be that, despite the fact that the Bullet script (second one) should be setting the damage to 10, it stays at 0, which might be related.
Log to see if anything is hit.
Or if the if-statement is true at all.
How to post !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.
It looks like the if (enemy) statement isn't returning true, but I don't know why since the enemy I am hitting does have the EnemyStats script.
Log is the sure way to go.
Debug.Log($"{name} hit {collider.name} that had a layer of {collider.gameObject.layer}");```
If this is false, nothing else would matter.
Collapse log if you're getting a great amount of spam.
ok
if two threads try and add an element to a global list at the same time do both go through?
Are you using threads?
yes?
you probably aren't using threads
Ensuring you're simply not misunderstanding stuff.
im modifying a tool that loads assets asynchronously
not 100% sure on the execution but I do know my code continues to run while the assets are in the process of loading
and I can subscribe functions to the OnLoaded event of individual bundles
There will be race conditions. Do not expect anything to be in any order.
order I dont mind as long as both get added to the list
my concern was something like both threads access a 9 length list and change length to 10, setting the 10th element at the same time
losing an entry
alternatively I can just have a void LoadNext run each time OnLoaded gets sent and force it to be synchronous
nvm I can just make it a dictionary, so no two threads should ever access the same key
how do I create a new key-value pair in my dictionary, where the value needs to be an array of a class?
Dictionary<string,ConnectedPieceClass[]> allConnectedPiecesDic = new Dictionary<string,ConnectedPieceClass[]>();
having trouble on the line below
allConnectedPiecesDic.Add(kvp.Key,new ConnectedPieceClass()[]);
you need to provide a length!
arrays have fixed lengths, after all
😠
perhaps you want a list instead
please ping me with response
I’m new to Unity and I have a few troubles.
I have a camera that can be moved with a rigid body, and two spheres. One sphere has a lens flare and lights component.
I want the camera to be able to move through the spheres, so I disabled sphere colliders. However, now the lens flare and light pass through the sphere without those components. Is there a way to have a sphere that lets a camera pass through it but not light/Lens flare?
thanks Ill take a look at this. The tool is coded pretty oddly, trying to understand is going nowhere
Use the layer matrix to mask what is allowed to collide, putting your camera and spheres on layers which don't.
I’ll look into that—thanks!
im loading prefab for editing with PrefabUtility.LoadPrefabContents
then trying to attach another prefab with PrefabUtility.InstantiatePrefab and passing loaded root transform as parent
then PrefabUtility.SaveAsPrefabAsset and nothing, checked with debugger, prefab reference is not null
nothing i mean the prefab is saved, but the instantiated one is not attached to it
anyone know how to make a card scrolling system that looks like you're scrolling along the side of a cylinder if that makes sense
my idea is to render cards in 3d space along the edges of a circle but prob overthinking it
huh apparently PrefabUtility.InstantiatePrefab "parent" argument does nothing in this case, have to explicitly SetParent
🫠
Thanks to you, I got it to work!
will this work as anticipated, quickly creating a Time.Deltatime timer (+1 each second)
no, you shouldn't be calling MonoBehaviour constructors manually
what is the purpose of this?
no, i literally just answered that
you said I shouldn't be making them manually, not whether or not it would make a timer
nvm
ill do this the other wat
*way
Timer.Update will never be called since you create Timer incorrectly like boxfriend says
literally the first word was no. the rest was an explanation
thank you for answering the question
that wasn't really an explanation but im to tired to argue rn
sorry, i assumed we were in #archived-code-general and i wouldn't need to explain every little detail about why you shouldn't be calling a monobehaviour ctor
where should I backup the save to the cloud? I want it to be synced up with the PC version, so I want to do it often enough, but I dont want to bloat the database by sending saves every minute.
Also I dont want a save button, currently the state (locally) is saved on specific events
how often do those events trigger to cause a save to happen?
then why not backup to cloud then?
idk, firebase seems expensive xd
1$ per gb downloaded
well
you are right, my problem is not the backup frequency
my problem is that currently the save can get very chonky
how are you currently serializing the data to be saved? and how much of that data actually needs to be saved in the first place?
json
and the data can be a few hundred kb after a few weeks of use
after minifying I can get it to 1/3rd
ah yeah, that'll be chunky. could always look into something like messagepack, it's pretty good about creating nice and small binaries. can even use compression too
are protobufs ok for serializing persistent data?
i've never used it but i don't see why not. message pack is typically smaller and faster than protobuf though
Hey guys, so I'm just writing up a player and camera controller however something happened to then led to this lol, anyone might have a clue to what has caused this? The camera isn't even centering on the target for some apparent reason.
message packs seem very neat tho, since you go directly from json to them
also, big part of the bloat in my json are DateTime objects, that get serialized as strings "2023-05-07T11:19:00"
could probably serialize them as a long, if I switch to messagepacks
i think by default messagepack also serializes datetime as strings, but you can use the nativeresolver instead
same for GUID and decimal
focusPosition must not be getting updated to the player pos
yeah I mean I could just serialize them as a property that is DateTime.Ticks
Hmm, I see. I can't seem to find the mistake in my script though
https://gdl.space/zayagoluya.cs
https://gdl.space/ujozitawoq.cs
^just in case if this helps at all
Hay in my script i set MoveEndTile as a refrence to a Tile object, but later i want to set it back to a reference to null, how do I do this without setting the tile object its refrencing to null?
you want to make it null
Why assign a Quaternion to a Vector3?
but you don't want to make it null?
i dont want to make the object null I want to make the variable null
transform.position += moveDir * moveSpeed * Time.deltaTime;```
Move direction is a quaternion. Why are you adding it to the Vector3 position?
oh wait nm i made a seperate mistake in my code that confused me about how setting a object works
I was accidentally also running SetActive("false") on the object
obj.SetActive(false) (not "false") would make the game object inactive
IK i wrote it incorrectly there my b
3d character rotation to follow the player coordinates
also i just noticed the event trigger "pointerdown" detects right, left and even middle clicks how do i specify what type of click? should add like an
if(Input.GetMouseButtonDown(prefmousebutton))```? or is there a way to do it from within the inspector in the event trigger component?
It should take an int as a parameter
Are playerprefs concidered acceptable for storing game settings?
I dont have much to worry about other than some common int values and booleans
that's what they're there for
prefs, stored by the player (rather than the editor)
(even though player prefs work in the editor)
Mmk, i made a custom save system for other things that uses its own file format and obfuscation. Sounds good
yes, i believe it's specifically for storing things that would go in the 'options' menu
it is not recommended for storing, say, save data, like player progress and inventory
That might be overkill for settings though, i need to get this ready asap for deadline
Mmk thanks. It seems like window settings like resolution and mode persist so im not storing those
I mean, if it's a small game that just needs to store which levels are unlocked it can work
Our game has a lot of unlocks and progress checking so i'm handling that without prefs lol
As for me, I'm tryna start the whole 'health' and 'take damage' system for my game.
I suppose I need an entity that deals damage (example, sword hitbox, or pitfall trap), and one that takes damage (player, enemy, or even wooden crates).
I guess what I need is, vague pointers on whether to use interfaces, class inheritance, or child gameobjects, etc.
What i like to do is have a script on players and enemies alike called CharacterAttributes that has common values like health, and what type they are "Player, Neutral, Enemy" and on that method have a public void TakeDamage(DamageInstance d); where DamageInstance is a struct that has whatever values you need like damageType, damageValue or even a reference to who the damage came from.
If you like inheritance and want to treat enemies differently, you could make EnemyAttributes which inherits from CharacterAttributes and overrides those methods like TakeDamage
You could also just use a simple number instead of damage structs, but i like to include context data so you can handle things like lifesteal and heal the owner
I have a situation in my game where there is a central hub with several portals. Then there are other scenes where the player must do some actions to unlock the portals. While the player is in such a scene, the hub scene is unloaded. How can I make a system where an event is invoked when the player unlocks the portal and then the portal opens once the main hub is loaded again? e.g. changing the material of the portal
I found PointerEventData.InputButton, but im not sure how to check it? like PointerEventData.InputButton cant be use as a variable so i can see if it like == left or however?
Ah, you multiplied it by the move input.
Not certain then, it shouldn't cause you to be teleporting around the area.
I think I want to avoid inheritance, notably because the player and some more complex enemies already inherit from StateMachine in my case.
But yeah now that I think about it, player taking damage and enemies taking damage will probably behave drastically differently... in terms of knockback, iframes, animations, statemachine etc.
maybe i'll just do an interface, since they won't have any underlying logic in common beyond "take damage" method.
okay i think i figured it out, i need to pass PointerEventData into the method that gets called then check that
NM if i try to do that, the event trigger does not recognize the method exists
Yep, just find a nice system that works.
Depending on the game it might be nice to have enemies able to use some of the same systems as the player
Hey guys,
I'm a bit stuck trying to get the formatting for a number correctly,
I pull a value from a server, say something like 5000000.
The number I fetch has 6 decimals, so that number above might only be 0.00005, however Unity doesn't show that?
I've tried string.format() and a few other tricks, but I can't seem to dynamically add the . if the value is less than 1.
Would anyone be able to give me a bit of direction?
Thank you!
I made an airlock door system that im very proud of
but the big problem is
that the box collider that triggers the door when a player goes near it
I have an aim transform
that goes wherever my aim transform points
and the aim transform doesnt go through the box collider trigger which I want it to
after quick google search, i believe
yourvalue.ToString("F6")
will print with six decimals
and if you need to sometimes render a decimal and sometimes not, i'd probably actually just write an if statement.
Thanks @rough horizon !
I completely tried over engineering that haha
i still need help how do i make the event trigger pass in anything usable?
OnPointerDown will pass a parameter of this type
you must already have it, or you'd get an error
Im using the event trigger component
k 1 sec
IPointerDownHandler does pass a PointerEventData parameter
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IPointerDownHandler.html
yeah, there's the one I wanted
yeah UI docs have been split into a separate area for whatever reason. i had to bookmark it because any other time i try to find them i only come across the old ones on the regular docs site
does this one actually tell you which mouse button was pressed?
ah, there it is
button
https://gdl.space/afezulonaj.cs this is my code and here is the event trigger
you should be able to accept PointerEventData as a parameter for those methods
then they'll show up in the Dynamic section when selecting a method to add a listener for
depends entirely on the question
wym dynamic section?
hm, it says BaseEventData in the unity events in the inspector, tho
I made an airlock door system that im very proud of
but the big problem is
that the box collider that triggers the door when a player goes near it
I have an aim transform
that goes wherever my aim transform points
and the aim transform doesnt go through the box collider trigger which I want it to
do you have to receive a BaseEventData and then downcast that to PointerEvenData? that sounds weird
oh and I fixed the whole thing
if i attempt to accept PointerEventData with the method it simply does not show up in the inspector
if i do i have 0 clue how to do that
this isn't really enough info. i have no idea what you mean by "the aim transform doesnt go through the box collider trigger"
in that case try BaseEventData and see what happens 🤔
I can accept base event data, it shows up under the dynamic section like you said
then you should be able to cast using the as keyword (or if you are using a modern unity version you could even use is in an if statement)
i.e. var data = baseData as PointerEventData;
it seems weird that it'd go this way...
if(nameofparameter is PointerEventData pointerData)
Ah okay
oh yeah
it's probably because the events are just stored in a list of EventTrigger.Entry and it has to support all of the events so using the base class for the event data would be necessary for that type to support all of them
i forgot to send the image
ah right
downcasting my unbeloved
think it worked with a
var pointerdata = baseData as PointerEventData;
if (pointerdata.button == 0 )
{//stuff
ty yall
to be more readable, you should use PointerEventData.InputButton.Left
i still don't know what you mean by "the aim transform doesnt go through the box collider trigger"
i still have no idea what the problem is
kk
is that circle winding up in the wrong place?
does anyone know why i have to change external script editor to visual studio every time I launch
you shouldn't have to change it every time. if you are quitting normally and it still resets every time, try launching unity with admin perms and set it then restart it as non-admin
I quit unity every day mentally
are you really even using unity if you haven't mentally quit at least once an hour
this was a painful day
When I shoot, the bullet hits the collider. how do I make it ignore the collision
by ignore the collision do you mean prevent OnTriggerEnter from being called, or do you mean it is actually physically colliding with the trigger collider
either way this should be useful: https://docs.unity3d.com/Manual/LayerBasedCollision.html
however if there is a physical collision happening with a trigger collider then either the collider isn't actually a trigger or you are using physics queries to determine where the object can move to but not filtering out trigger colliders
Is the animators locked in sync with the update or fixedupdate? I have code running for hitboxes, and movement that is locked into set numbers, should I excute it in the fixed update, or will it be fine in the normal update loop? Just unsure about how code runs in tandem to animations
animators update every frame
up to you - it's a setting
by default, at least
there is indeed a setting
https://docs.unity3d.com/Manual/ExecutionOrder.html is the default behavior
Will changing it to animate physics change the quality of the animation at all seeing as it would be a fixed 50fps?
probably
what is "movement that is locked into set numbers"?
Sorry, moves that have set vector3s and float associated with it at what time they will sequence through, but its fine I think I got my answer, thanks for the documentation
physically
then either the collider isn't actually a trigger, or like i mentioned you may be moving based on raycast (or other physics query) hits and not filtering out trigger colliders
Hey guys!
One more quick question,
Is it possible to parse a BigInteger into a float? 🙂
no but itsnt there like an IgnoreCollision()
Parse it? No, it's not a string.
You can do an explicit conversion though https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger.op_explicit?view=net-8.0#system-numerics-biginteger-op-explicit(system-numerics-biginteger)-system-single
probably not a good idea in general since BigInteger can hold much larger numbers than float can with any degree of accuracy
just use the layer based collision instead. but again, if it is a trigger collider then there should not be physical collisions happening with it
if it's a trigger collider, then your bullet is not colliding with it
Thank you for the input!
Noted down @leaden ice
perhaps you are getting a trigger event and stopping the bullet in response
then why is my aim transform colliding with it
i still don't understand what your "aim transform" is
it's not the bullet?
is it something that you're positioning with a raycast?
yes
then tell the raycast to 1) ignore the layers it shouldn't hit 2) ignore trigger colliders
i just looked at that link
where would I put the exclusion
would I just do queryTriggerInteraction = false?
no
oh
read the documentation.
thrice.
you must make the effort to read what's being shown to you.
what does this mean: QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal
this is the default value for that parameter
the parameter's type is QueryTriggerInteraction, and the parameter is named queryTriggerInteraction
the default value is QueryTriggerInteraction.UseGlobal
correct
you should also be passing a layer mask so that your raycast only hits things that make sense
i.e. the map and enemies, probably
yeah
do you know of a good way to acomplish a brawl stars like matchmaking system with netcode
if u even know what that is
idk about the netcode aspect
i'd expect matchmaking to just be a server that people tell "hey, I want to play", and that then later tells the clients when it's found a match
bit of a large question to ask, though
multiplayer is so insane to develope it hurts
Don't do it
unless you're doing it with others
in a professional setting
else pain
is it ok to have both rigidbody and character controller on the same gameobject?
Trying to get OnDrop to work consistently is insanely frustrating
Sometimes it works, othertimes you'll drop something right on it and it won't count
Is it based on your mouse position or on the object you're dragging?
pretty sure they're gonna fight
like if i just use rb to track velocity
not any .addforce shenanigans
you can already get .velocity from the character controller
what are you trying to do here? the character controller is used explicitly to avoid having a physically-simulated player
it respects colliders, but it doesn't get affected by physics forces
idk i just need to sync the velocity between server and client
and this is the simplist solution i thought of
might i recommend the KinematicCharacterController which allows you to just get and set its state so you can easily pass the state to the server from the client and vice versa without any weird fuckery.
it's also much better than the built in CC imo, though it is a bit more advanced
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
i've been having a good time with the KCC so far
tbh didnt know it was a thing
i want to do that but im not going to because then i have to rewrite all of my code again
yes
you're gonna have to get used to this
and im still lazy
then you are not writing a multiplayer game
i had to remake it from scratch again because netcode was a pain in the ass
il look at the kcc
Im attempting to make a function that i can use to change the FOV of the camera, but for the FOV to lerp smoothly i need to keep the * Time.deltaTime at the end. However this crashes unity. How might i get around this. I have tried making a Coroutine instead but when i do that its rlly buggy and the FOV never truly hits the targetFOV and just kinda sits in between the two values and buggs out
Here is the Coroutine i attempted to create instead
The first is an infinite loop that would crash the Unity Editor application
Your lerp is incorrect in both.
your current parameters would be better with Mathf.MoveTowards instead of Lerp since they are not currently linear
If you do not need to traverse in reverse, I'd suggest simply adding steps in delta.
Smooth damp can create dampening if you need damping.
how is it an infinite loop if im chaning the camera fov to be = to targetFov which would satisfy the condition
Your lerp isn't proper, you'll never reach the destination - truly.
I suggest simply not using lerp and simply using move towards unless you're needing to traverse backwards
wdym by traverse backwards
Same thing but requires less setup
cause i change the fov from like 75 to like 90 and back to 75 if thats what u mean
Lerp's third parameter isn't how much to move this frame. It's where you are in the linear interpolation.
Where 0 is at the initial position and 1 would be at the final position.
Where your first argument would be a copy of the initial position - not your current position. The second argument would be your final position.
The improper way to lerp has folks using current position as the first argument and some fraction as the third argument.
For example, if the third argument is 0.5f you'll simply reduce the distance between you and the target by half each call but you'll never be at the target ever (you'll never have a progress of 1.f).
In your case, it's not necessary to lerp. Just use move towards https://docs.unity3d.com/ScriptReference/Mathf.MoveTowards.html or smooth damp (more complex/effort) https://docs.unity3d.com/ScriptReference/Mathf.SmoothDamp.html
Also, if you want to compare float.. try using https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
I'm having issues with my car's wheels wobbling around alot when im driving. I am using a wheel collider. What could be causing this?
It doesnt seem to be the collider that is wobbling because the car isnt affected but the meshes sure do look strange
Heres the code for each individual wheel:
{
if (Input.GetAxis("Vertical") <= 0)
{
wcol.brakeTorque = Input.GetAxis("Vertical") * brakeForce;
}
if (Input.GetAxis("Vertical") >= 0)
{
wcol.motorTorque = Input.GetAxis("Vertical") * power * -1;
}
if (steering)
{
wcol.steerAngle = Input.GetAxis("Horizontal") * steeringRatio;
}
Vector3 pos = transform.position;
Quaternion rot = transform.rotation;
wcol.GetWorldPose(out pos, out rot);
wtra.transform.position = pos;
wtra.transform.rotation = rot;
}```
Is the pivot of the model in the center ?
Yeah
Try using a sphere instead.
Does it interact with the model of the car ?
Try to disable collision between them.
No, the part that is wobbling is just a mesh and has no physical impact on the rest of the car.
So, the collider is correct ?
Alright will do
one second
It is perfectly smooth with a sphere
so that means my wheel model is dodgy?
Yes, it probably means the the pivot is not in the center or the model is not symmetric.
I think this may be my issue in blender, the cursor is not at 0,0 which is where the centre of my wheel is.
Is the wheel really symmetric ? You may have made a mistake. Try to export a sphere.
oh yeah you are right, this is what it looks like when mirrored
ill just make a new wheel lol
thanks for the help 😃
wiggly
How would I make particles stay after the particle system's parent has been disabled? I can't find something I can use online
the particle system renders the particles
so, you ain't gonna disable that without losing the particles
what are you trying to do? stop spawning particles?
I'm trying to have an effect that occurs after another object disappears
i would just stick the effect on a separate game object
I don't think that would work well since it's in an object pool and there are multiple instances of the object
sure, spawn several instances of the effect.
i guess you could also pool the effect objects, if you really wanted to do that
I'll try, gimmie a sec
I have an issue with Rigidbody2D.Addforce, where it's acting basically as .velocity. In my game it's supposed to be for a jump feature but for some reason it isn't working. I've haven't had this issue before. When I press the button to jump and the jumpHeight is over 20, it increases velocity.y far beyond where it's supposed to go and caps out at 5000, this is all I have to make it jump (Other than the calling of the function).
void Jump()
{
rb.AddForce(new Vector2(0, 1) * jumpHeight);
}
Use the impulse forcemode
Are you calling it every frame?
From the video it looks like the velocity is overriden somewhere else.
Probably your movement and jumping logic mess up each other.
Hey guys, so I'm making this retro style game and need the animations to look choppy like 1-2 frames. I've created scripts to enable one image and disable the other but the problem with my game is that it consists of a series of canvases rather than scenes so the animation is in a canvas that will be activated later in the game but regardless, the animation plays when the game loads at the start because it's not hooked up to a button or anything, I just want it to play when the canvas is enabled, but with a delay.
What canvases? Canvases are normally used for ui.
Either way, just don't play the animation on start. Play it when you want it to play.🤷♂️
Yea my game is just a 2D point and click adventure so I just used canvases. I tried to make it play on Awake but that also didn't work because I all the canvases are loaded at the beginning and then disabled and reenabled one by one.
So it thinks that it should play at the beginning
But I thought that it should still reset and then work when it's awoken again?
First of all, canvases are not for 2d gameplay, they're for ui.
Second, don't play it in Awake or Start. Instead, play it when you progress in your game to the right point.
Depends. I've no clue how you have it implemented ATM.
From the sound of it, you just swap sprites manually. That wouldn't reverse/reset unless you tell it to.
Oooh ok thanks I just need to reverse it
Thanks! That was it.
Fixed it, I just made all the canvases disabled from the start and it worked
private IEnumerator SteppedOn()
{
yield return new WaitForSeconds(2f);
if (Physics.CheckSphere(transform.position, outerExplosionRadius, playerMask))
{
playerHealth.ReceiveDamage(15);
if (Physics.CheckSphere(transform.position, medialExplosionRadius, playerMask))
{
playerHealth.ReceiveDamage(20);
if (Physics.CheckSphere(transform.position, innerExplosionRadius, playerMask))
{
playerHealth.ReceiveDamage(50);
}
}
}
Destroy(gameObject);
}
trying to make a landmine. right now it only does 15 damage even if Im in the inner circle
Why not just use Vector3.Distance once
I got it to work thanks to chatgpt, I just cant execute playerhealth.receivedamage that much
and I didn't think of vector3.distance, still not used to game programming but that is a good idea
I thought about it too literally lol
{
if (other.tag == "Grape")
{
Destroy(other.gameObject);
health += 0.1f;
healthbar.SetSize(health);
count++;
countText.text = "count: " + count.ToString();
}
if (other.tag == "Bannana")
{
Destroy(other.gameObject);
health += 0.1f;
healthbar.SetSize(health);
count++;
countText.text = "count: " + count.ToString();
}
else if(other.tag == "Donut")
{
Destroy(other.gameObject);
health -= 0.1f;
healthbar.SetSize(health);
}```
I'm trying to have the character destroy the item labled "Bannana"
I've had the "Grape" work, however the "Bannana Item wont disappear after the player touches it. I'll need to respell banana.
Log what you hit and see if it was a banana.
Debug.Log($"{name} hit {other.name} that had a tag of {other.tag}");```
Have the logs on collapse if you're receiving too much spam from the console.
The same save file being used between the built version of my game and the editor ends up producing different results when loaded though I'm not entirely sure why
The code that loads the file:
public void LoadGame()
{
GameData data = Save_Load.Load();
Player_Settings settings = Save_Load.Load_Settings();
if (data != null && settings != null)
{
transform.position = new Vector3(data.RespawnPos[0], data.RespawnPos[1], 0);
HP = data.PlayerTotalHP;
CurrentHP = HP;
shot_controller.has_gun = data.has_gun;
shot_controller.has_shotgun = data.Has_Shotty;
if (data.Has_Shotty == true) GameObject.Find("Shotgun Acquire").transform.position = new Vector3(600, 600, 600);
QuarterHpPickups = data.QuarterPickups;
Checkpoint.x = data.RespawnPos[0];
Checkpoint.y = data.RespawnPos[1];
Checkpoint.z = data.RespawnPos[2];
int x = 0;
foreach (Cutscene_Control script in FindObjectsOfType<Cutscene_Control>())
{
script.HasBeenTriggered = data.CutsceneTriggers[x];
if (data.CutsceneTriggers[x] == true) script.MoveCamera();
x++;
}
int a = 0;
foreach (Upgrade_Behaviour upgrade in FindObjectsOfType<Upgrade_Behaviour>())
{
upgrade.Taken = data.upgrades[a];
upgrade.Move();
a++;
}
int z = 0;
foreach (ReceptacleAndBall receptacle in FindObjectsOfType<ReceptacleAndBall>())
{
if (data.triggeredEnvironment[z] == true) receptacle.Activate();
z++;
}
int y = 0;
foreach (BaseBossBehaviour baseClass in FindObjectsOfType<BaseBossBehaviour>())
{
if (data.bossKills[y] == true) baseClass.Die();
y++;
}
}
}```
May want to inform folks how they differ in detail so people have got a clue what to look for rather than just simply looking for a mistake that may not exist.
Say I have 2 instances of the Upgrade_Behaviour script and I collect the first before saving in the editor
if I were to load, the first would be taken, the second is untouched
however if I were to use the exact same file that I saved from the editor in the built game
loading would cause the first to remain and the second to be taken
and vice-versa for if the save were made in the build and used in the editor
Main difference between build and editor would be folder/file structure.
Maybe the save isn't present for the build.
Same saves for both
Is the path dependable?
If you're just saving to the root, the build will not have the save file.
same path for both
The information is missing thus why I'm asking
specifically it uses the persistent data path bit
Without looking more into the code above, would the game load the second if no save files were present?
nope
So when does the game load the first?
Well, relative to the code above.. this would be the only section related to upgrade behavior: cs int a = 0; foreach (Upgrade_Behaviour upgrade in FindObjectsOfType<Upgrade_Behaviour>()) { upgrade.Taken = data.upgrades[a]; upgrade.Move(); a++; }
data is referenced from de-serializing the save file, if that's null then this block never gets run
Why explicitly FindObjectsOfType rather than FindObjectsByType?
It is recommended to use Object.FindObjectsByType instead. This replacement allows you to specify whether to sort the resulting array. FindObjectsOfType() always sorts by InstanceID, so calling FindObjectsByType(FindObjectsSortMode.InstanceID) produces identical results. If you specify not to sort the array, the function runs significantly faster, however, the order of the results can change between calls.
Simple
I didn't know the other existed
Though I rely upon the assumption that everytime I call that function
the resulting array of objects that's returned is always in the same order
You're going to have to attach the debugger to the build and log data from the data upgrades.
Likely the data isn't what we're expecting or there's some sort of race condition elsewhere.
This code won't likely change itself.
Race condition?
Some other dependency may be altering the result.
I've got no other suggestions as I've only seen this method
so could it be that there's differing instance IDs between the editor and build?
I have had this exact code work in the past and I haven't changed anything in regards to those objects being accessed by other scripts
Because assuming a build made save is used in the build and the same for one made in the editor
it remains consistent and I can't observe any odd behaviour
I want to give a script a component and then i want to be able to choose a void to trigger from the editor. how would i do this?
UnityEvent..?
Yes! thank you
how does this not work
Your parameter is called collision, not other
thanks
Also you should use CompareTag, it's more performant and warns you if the tag doesn't exist.
if (collision.CompareTag("collectable"))
I'm currently procedurally generating 25 islands and storing the positions of every single block being used to make up the islands so that I can instantiate scenery etc. So far it works fine but now I need to find a way to track each 40x40 island so that I can individually reference them instead of just referencing a single block within them. My current code is as follows: https://gdl.space/ravotidije.cs I've added a few comments to make it easier to see what I was going for but I'm stuck with an error telling me I can't convert a list to a Vector3 (which will be due to the way I'm trying to store the islands). Could someone take a peak and give me some pointers on what I should be looking at trying? Cheers
I'm not sure if any snippets of code are needed, but I'm currently using object pooling just to learn how to and my current project is a sort of sorting game where I press a number and drop an item into a box where the item gets set inactive to put it back into the pool to be reinstanciated. However, I'm running into an issue where when I call a game object such as a sphere with object pooling, they seem to carry their momentum from when they were first called. I.E the Sphere got booped and now has momentum towards the right, when that object gets called again to be dropped straight down, it'll carry the momentum from when it got hit to the right. Is there a way I can reset the momentum or would I have to have force on the rigidbody with a normalized speed pushing it straight down to achieve the desired goal?
Show us the actual error.
Set it's velocity to zero.
vertices[v + 1] = new Vector3(vertexOffset, heightValue, vertexOffset) + cellOffset + gridOffset;
vertices[v + 2] = new Vector3(vertexOffset, heightEast , -vertexOffset) + cellOffset + gridOffset;
vertices[v + 3] = new Vector3(vertexOffset, heightEast, vertexOffset) + cellOffset + gridOffset; ```
im trying to add a 0,125 bezel to my mesh generator, i've tried
```cs heightEast + 0,125```
but the problem is that with my current code im using the same formula if the height destination is either higher or lower and adding a constant in this way doesnt work in both directions
I literally do not know why I didn't think about this lol, thank you
Hello guys, is it possible to create Input in play mode test for testing the behavior of my characters responding to the user inputs ?
private void Reset()
{
Restart:
id = Random.Range(-32000.0f, 32000.0f);
foreach (Upgrade_Behaviour upgrade in FindObjectsByType<Upgrade_Behaviour>(FindObjectsSortMode.None)) if (upgrade.ID == id && upgrade != this) goto Restart;
identity = id;
}
is there any way to get this code block to run whenever I drag in an instance with the class attached?
such as through dragging in a prefab with the class attached to it
Obviously Reset isn't the right function for it
does anyone know how rust does this?
Which part of that picture is "this"?
Hi guys.
Can anyone help me figure out how I can lower the speed at which one of my game objects moves based on how close it is from its the target position?
Like, the object moves towards a target position with speed 5, but I would like to have it slowly go to 4 the moment the distance between the object and the target position is lower than 1.5f or something.
uhh the character model
like
when they go into the inventory they show a version of the character model so when you equip the armour it shows it on the character
this code should also only run once when the object is first created in inspector and then never again including when the game gets built for consistency between the two
Google for "3d models on top of ui unity"
alrighty
Howdy all! A bit of a newbie question here: How can I add/declare a list inside my class list?
public class TargetClass
{
public GameObject targetGameObject;
public TargetClass(GameObject _aiGameObject, // List for waiting)
{
targetGameObject = _targetGameObject;
// here a list for waiting
}
}
public static List<TargetClass> targetList = new List<TargetClass>();
Sure, here it is: Assets\GenerateGrid.cs(63,41): error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.List<UnityEngine.Vector3>' to 'UnityEngine.Vector3'
Which one is generally preferred?
readonly Stack<OverlayData> _overlays = new();
public struct OverlayData {
public string Header;
public string Subtitle;
public Overlay Instance;
}
readonly Stack<(string Header, string Subtitle, Overlay Instance)> _overlays = new();
```This feels like a small thing but that people have *very* strong opinions about
public class TargetClass
{
public GameObject targetGameObject;
public List<...> list;
public TargetClass(GameObject _aiGameObject, List<...> _list)
{
targetGameObject = _targetGameObject;
list = _list;
}
}
```Do you mean this?
Or do you want to add all the instances of this class to the list at the bottom?
Yep I think so indeed
I was fiddling with it like this
public class TargetClass
{
public GameObject targetGameObject;
public TargetClass(GameObject _targetGameObject, )
{
targetGameObject = _targetGameObject;
// here a list for waiting
List<GameObject> waitingQue = new List<GameObject>();
}
}
public static List<TargetClass> targetList = new List<TargetClass>();
The "correct" way to do this is actually
public class TargetClass
{
public GameObject targetGameObject;
public List<...> list;
public TargetClass(GameObject _aiGameObject, IEnumerable<...> _list)
{
targetGameObject = _targetGameObject;
list = _list as List<...> ?? _list.ToList();
}
}
```Because the `IEnumerable` class allows for more flexibility, for example being able to pass an array instead of a list
The new List<GameObject>() new list isn't even needed?
Depends on if you pass the list through the constructor like I showed
If you're just going to pass an empty list, you can instead create it like that
public class TargetClass
{
public GameObject targetGameObject;
public List<GameObject> list;
public TargetClass(GameObject _aiGameObject)
{
targetGameObject = _targetGameObject;
list = new List<GameObject>();
}
}
Yeah creating a new list, think I need the bottom one
This one? public static List<TargetClass> targetList = new List<TargetClass>();
That's the parent class list
Oh you meant the bottom code I sent
Yeah, that would be the best one if you want a new list
targetList[0].targetGameObject
targetList[0].waitingQue[0]
those I gonna need when the list is finished
after I put objects in it ofcourse XD
Should work 👍
Thanks for the help buddy!
Just remember to actually add the instances to the parent class list
Oooh wait then I need the other example right?
public class TargetClass
{
public GameObject targetGameObject;
public List<GameObject> waitingQue = new List<GameObject>();
public TargetClass(GameObject _targetGameObject, List<GameObject> _waitingQue)
{
targetGameObject = _targetGameObject;
// here a list for waiting
waitingQue = _waitingQue;
}
}
public static List<TargetClass> targetList = new List<TargetClass>();
wauw I'm confused XD (smoke brb)
Yeah I think the example above should work
No I gonna need this one I think
Hello everyone !
I have a question : Which is these two lines of codes is usually better ?
// OR
transform.RotateAround(casterTransform.position, Vector3.forward, angleSpeed * Time.fixedDeltaTime);```
I'd say the second one is more readable. Maybe split it into several lines though.
Maybe split it into several lines though
How so ?
I think like this, but I'm a newbie so should wait for confirmation.
transform.RotateAround(casterTransform.position,
Vector3.forward, angleSpeed *
Time.fixedDeltaTime);
if (heightEast != heightValue)
{
for (int i = 0; i < 3; i++)
{
vertices[v] = new Vector3(vertexOffset, heightValue + i * ((heightEast - heightValue) / 3), -vertexOffset) + cellOffset + gridOffset;
vertices[v + 1] = new Vector3(vertexOffset, heightValue + i * ((heightEast - heightValue) / 3), vertexOffset) + cellOffset + gridOffset;
vertices[v + 2] = new Vector3(vertexOffset, heightValue + (i + 1) * ((heightEast - heightValue) / 3), -vertexOffset) + cellOffset + gridOffset;
vertices[v + 3] = new Vector3(vertexOffset, heightValue + (i + 1) * ((heightEast - heightValue) / 3), vertexOffset) + cellOffset + gridOffset; ```
how can i adjust this code so the top and bottom face are smaller and the middle one gets stretched between them?
Something like this:
var pivot = casterTransform.position;
var rotation = angleSpeed * Time.fixedDeltaTime;
transform.RotateAround(pivot, Vector3.forward, rotation);
Hi, good day.
I have a little problem with coroutines.
I have a method that start a coroutine that starts some on its own.
If a button is pressed i want to stop all those coroutines to start again.
How could i do that? As far as i know i could do it by name but, is there any recursive way to destroy all the coroutines that were called by one method?
this nukes every coroutine that a behaviour has
alternatively, make a List<Coroutine> and put the coroutines you want to cancel in it
then just iterate over it and stop all of them
I think i can nuke them.
All the coroutines are started from a manager object and i want to destroy them in that object so this could work. I will try, thanks
Coroutines are always running on a specific behaviour
so you'll need to stop them on whichever behaviour you called StartCoroutine on
Just to make sure i understand that. If i called them from a gameobject script i can only stop them from inside that gameobject (not necessarily the same script)?
doesn't seem horrendous
I would make it so that it only runs when you actually need to toggle the UI
Is there anyway of provoking the OnValueChanged of a dropdown menu when selecting the same option again?
would not worry about it, but if you are worried just have build the list of gameobjects once and loop it later
though would be better off just setting up a event that triggers when armourPanel.activeSelf changes
tbf yeah
might be fine though
should i bother with a dedicated UI manager that handles dialog, menu settings and inventory UI, or just have pieces of code that do the same things but less centralized?
my game is incredibly light on the UI (only basics like the inventory, settings and some display options)
ive split mine up into 2 diff scripts but they are both singletons so they can communicate back and forth
but they both sit on the Main player
i generally have dedicated logic for UI, and i keep that logic fairly dumb just so things can call it and easily change what he UI is displaying or have it just listen for events
hi um is it better to use Visual Studio 2022 or Visual Studio Code with Unity?
Visual Studio 2022
Anyone who knows of a good tutorial showing how to fill a tilemap using a rule tile?
did you look online ?
i use vs code since it load faster on my pc....
Well yes, I missed a crucial word there though, I want to fill it using perlin noise, but I guess my question would rather be, "is it possible to use a rule tile like a normal tile in that regard when populating a tilemap using code and not the editor and how would that look like?"
Since I how it's nice to just configure the rule tile in one space and the editor just place the type of tile it needs there
Getting an UnauthorizedAccessException when attempting to write my game data to the disk:
public static void SaveWorldData(WorldData wd)
{
if (!Directory.Exists("worlds")) Directory.CreateDirectory("worlds");
string location = $"worlds/{wd.name}";
string json = JsonUtility.ToJson(wd);
StreamWriter sw = new StreamWriter(location);
sw.Write(json);
}
Try File.WriteAllText
That's what I tried first, same results
Uh
I never encountered that issue before so i don't really know how to help
Maybe the target path is protected?
Tried running as admin, adjusting permissions on the folder.
sorry to distract you, I can ask you why my code doesn't work and how to fix this error: https://media.discordapp.net/attachments/1043529513172213780/1105139517284958228/image-932.jpg?width=971&height=572
!code
Dyno asleep
If those libraries are throwing issues, that's an issue with the library.
Not an issue with anything you've done.
First post the code in a proper way
? how
!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.
It looks like you need an instance of the WebBrowser class to access all of those methods as they're not static
Is there any way at all to affect how the properties of a transform component are serialized in the editor?
its 600 700 lines
iirc csharp works too
Jesus fuck guys my goddamn bad.
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
I can't really see it on mobile
so idk if it worked
I guess it didn't
Null, fucking chill dude.
what are you trying to do?
like that https://gdl.space/pabonizani.cs ?
@potent sleet temporarily display world space coordinates rather than local for children
and possibly directly assign ws coordinates while thats going on
you could write an editor script
I've never tried before but, nothing is stopping you from inheriting from a Unity component like Transform right?
How to do it ?
this is the wrong script bud
not the one in the error
useful methods you can use
I am in an issue
My game has a level system and has levels stored in containers, the containers store all the data about the level and are loaded up when selected, the problem is I want my game to have 2 level systems and currently I am doing is if the level on the level screen selected had number 1 then load level number 1 and its getting a little strange as I am not able to understand how can I load the same type of file with the same name but with different data in a differenet level system, I have never made a level system before please tell if I am making any mistakes
The method I was using is now even interfering with my level editor that I made for the game
it's unclear from your description but it seems like you haven't really fully thought out your data model and/or system here.
what does "different level system" mean?
One level system will load up normal classic levels of the game and the other one is supposed to load up levels on daily basis
I don't really know what that means
but how are "classic" and "daily" levels different?
Like the normal level system unlocks level once you complete the previous one and the daily one will unlock once the next day starts
Sounds like the levels are all the same but you're describing different systems for unlocking them. Shouldn't they all be represented in the same way then?
I am categorising levels in 2 forms, the game is like match 3 game which has levels and once you complete level 1, level 2 unlocks
Whereas I am implementing a different level system where if you finished level 1 then level 2 will unlock the next day and I want to keep both of them
Yeah just sounds like you need to separate the concept of a level itself from how that level gets unlocked
Thats the hard part the levels are different in both
different how
Thats the question I am here for , cuz I am not able to implement them to open different level
This chat really isnt going anywhere
for some reason i keep getting this error when using vector3 and quaternion
The error is because vector 3 and quaternion exists in 2 name spaces and the 2 are mentioned in the error, it is asking you to specify that you are using Vector 3 from which namespace
well you'd have to explain to us, because we know nothing about your game.
delete using System.Numerics;
you added it by accident
and you don't want it
thanks
how did you know that your brain is so big you could just see the future
Let me explain from the start
There is a level select screen which opens some set of levels and the levels in that are unlocked like any other game , complete the previous one and the next will unlock.
And there is another level select screen in the same scene that will unlock level 1 on jan 1, 2024 and level 2 on jan 2, 2024 and so on.
The levels will be fifferent in both level selectors as I want users to play special levels on festival days which are specially decorated
My implementation for the level select screen is that if I clicked level 1 then it will look for the data that has int 1 and will load it and now I am confused how can I implement the second level selection screen which unlocks levels on daily basis.
Is there a better implementatuon for level selection?
seen it before :p
well, the error also explicitly explains the problem
Does anyone know how I can get an event from a static script to trigger something in my non static game manager script? I have a static level editor script that creates a custom window for my game and I would like an event to be triggered in my game manager when I press a button in the level editor
I don't think I can give the level editor a reference to my game manager like I normally would because it is static
static events that your game manager subs to
How would I do that?
hey there what is the current state of fixedstring
cant seem to access the struct but it does exist
it says it's in the unity.collections but it does not find it
public NetworkVariable<FixedString32> playerName = new NetworkVariable<FixedString32>();
static events would just be
public static Action OnSomething:
// invoke like
onSomething.Invoke();
// Subscribe like
onSomething += () => {Debug.Log("This lambda gets exectued when you invoke onsomething");}
Unless you are talking about editor scripts
it is an editor script
Is the editor script attached to a gameobject?
Looks like you can just use Object.FindObjectOfType
I'll try that, thanks
Why is this never firing??
do you have a Graphic Raycaster on canvas ?
do you have Event System
Yes, yes, and nothing should be blocking raycasts either
is raycast target enabled on this Image component
does anyone know how to easily save things
try debugging the Event System in Playmode and check what you're actually hovering
The target and the draggable object are on different canvas, thought I put them on the same canvas and it still didn't work
Er, how to do that?
go to Playmode, find event system in the scene , look at inspector, expand the bottom Window that says Event System or sum
it should expand the panel to view your mouse ray
also here is draggableobject
Ah, needed to disable raycast target on all the subcomponents of my draggableobject
this is a handy tip
ahh wops I was gonna suggest that next xD
👍
I am receiving this error and not sure why, the code looks fine and I've made sure that the navmesh is baked. I thought maybe it was because the script and navmeshagent were on the gameobject that is used to store the guards, but that doesn't seem to be the problem either. What am I doing wrong?
you seem to be calling SetDestination on an agent that is disabled / not on navmesh
but that's the thing - it has to be, as the code before this I made it chase the player regardless of position. the moment I'm trying to make it patrol before doing so, it says this, which I'm not understanding
well, is it on a navmesh?
make sure the enemy isn't floating above the navmesh, for example
yep
where is the enemy?
also, ensure that the error is coming from the instance you think it's coming from
i think that, if you click on the error message while the game is running, the offending object will be highlighted in the hierarchy
where is the navmesh agent component
nah only opens visual studio
single click
of the guard? here
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this can fix the erros but not the problem
if(_Agent.isOnNavMesh) _Agent.SetDestination(point);
I have Item class and have a weapon class that have the item as inherence class
How can i add that weapon as a item in my List<Item> charInventory;
charInventory.Add(theWeapon)
try checking the agents position before calling SetDestination
I though that because the class was Weapon it couldnt, but it worked
Thanks
well, it's set to (0,0,0) by default before any other position is set. I cna show you the documentation I was trying to use if you want?
sure
0,0,0 is default world pos, is your navmesh anywhere near that
and this since I did use it too:
https://github.com/JonDevTutorial/RandomNavMeshMovement/blob/main/RandomMovement.cs
where do you see 000 tho
oh I meant within the scene, my bad, the actual capsule's position is 000, I don't touch it within the code
no I meant Debug.Log(_Agent.transform.position)
so you know where it is before you run SetDestination
I'll run it rn
I don't know if I'm just having a massive brainfart or what but I literally just cannot think of a solution. Lets say I wanted something to get more red the closer it was to a value how would I do that?
Obviously health starts at 100 but I want it to be more red the closer it is to 0 not 100
this what I'm getting atm
if(health < 30) //Color = moreRed
etc
ops
I wanted to change dynamically
Which is why I cant figure out a math solution for it lol
wdym "dynamically"
So like lets say an object is about 10 units away from a sphere
You should also use SamplePosition to make sure your agent is on the navmesh
The closer it gets to that sphere the more red it gets
is it not ?
it's only on the random point though
https://hastebin.com/share/uhigikowos.csharp
Yeah gotta use it on the start position too
if(NavMesh.SamplePosition(...)) transform.position = hit.point
If hes getting the error about the agent not being on the navmesh, that is
yeah i would def check _Target too
so use vector3.distance
so you're asking me to do this intead?
but this wouldn't work, wouldn't that make the position of the current guard the hit position?
Not telling you to change anything existing. Just sample from your transform.position and set the transform.position to that sampled value.
This is how you make sure that the agent is on the navmesh
Then again I didnt read your whole convo so idk if thats even the issue?
it is 😭
Is the agent not active or has it not been placed on the nav mesh?
like this?
Yeah that should do
bet
yeah I'll crank it up to 5
well shit, I turned it up to 5 and it's somehow too far away 😂
hello, i'm trying to capture mouse clicks in the scene window from an editor window that i open up from the menu. im adding the following code to both the OnGUI() methods, as well as OnSceneGUI(), but it only captures clicks on the editor window itself, and not in the scene view. any ideas why?
Event e = Event.current; if (e != null & e.type == EventType.MouseDown && e.button == 0) { Debug.Log("sup2"); }
even if I turn it up to 20 it still says it's too far away wtf??
Something else is not right. Agent settings, maybe multiple nav meshes idk
Draw a debug line from transform.position to the new position?
Debug.DrawLine(transform.position, hit.point, Color.magenta, 10f); inside the if statement
Did you also make sure that there are no extra objects with this script?
I have, there are no extra objects with this script
I placed it there but it doesn't seem to be drawing the line
Where did you put the debug line, and is that code even running? Make sure it is
I did, I put it here, to find the new point
It was supposed to go here
anyone have any ideas about this?
still don't see anything
i dunno why the capsule goes through the floor either
Maybe try #↕️┃editor-extensions
thanks!
Because your object's pivot is in the capsule center. Thats just how the default capsule is
You can put the capsule on a child and move the child up
Maybe
tbh that capsule gizmos is not even showing the navmesh agent component cilinder
can you show me this component selected in the scene and screenshot whole scene showing hierarchy too
Thats not a method but a bool
I think you have to make that true so that changes to transform.position will affect it?
yea just notices 😅
sure
Not sure tbh, I dont work with agents, just navmesh
I just remember the navmesh agent component controls the transform and not other way around, like CC and Rb
oh ok, can you show same thing but in scene playmode
this is still worth a shot btw
#archived-code-general message
not sure if you tried it
yeah hes in the ground lol
i did, but like you said, fixed the error and not the problem
you can also use this
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.Warp.html
instead of transform.position =
it returns a bool
like SamplePosition
but it returns if result was success
but I've already made the capsule a child of the gameobject "guards" and I'm not sure why it's making it go through the floor if it's position of y is set to 1, which is above the floor
the pivot is in the middle
you have to warp the agent to pos not the transform in this case
I don't think I understand sorry, how will using the bool help
did you read the page i sent you at all ?
it's a boolean, use it to see if that will work. if it doesn't then trnsform.position is wrong spot
if(_Agent.Warp(hit.position){
//
Debug.Log("Warped");
}
else{
Debug.Log($"Cannot teleport {name} to {hit.position} - Distance from agent is {hit.distance}.");
}
How can I grab a scriptable object's data from another script
like a level select, where it gets all the maps with their scriptable objects
Hmm mind showing the script with the data
using UnityEngine;
[CreateAssetMenu(fileName = "NewLevel", menuName = "Level")]
public class Level : ScriptableObject
{
/*
* This class represents a level in a game. It contains information about the level such as the thumbnail image,
* the level name, the level description, and any other relevant information.
*/
// The thumbnail image for the level
public Sprite thumbnailImage;
// The name of the level
public string levelName;
// The description of the level
public string levelDescription;
// Any other relevant information about the level
public string otherInfo;
}
you're right, it's the wrong spot, but I'm not sure why it's trying to spawn it there
Hey guys. Anyone familiar with the A* Pathfinding Project by Aron Granberg?
I'm using it to follow an object around in my scene but I would like to make its speed constant, which by default is not. Not sure what I need to do to fix that though.
you get a reference to the ScriptableObject instance. conveniently instances of scriptable objects are usually assets you can just drag into the right slot in the inspector
That's just the base class of the scriptable object, you need to add references to the SOs you have created in the level selector script.
Like this:
public Level level1
public Level level2
can you send link to new updated script
assuming you are using the default AIPath component that comes with it, you probably need to adjust the maxAcceleration and slowdownDistance
https://arongranberg.com/astar/docs/aipath.html
use a List/array so it can be modular
Yeah so you don't have a wall of variables when your level count gets higher
yeah you mean this xD ?
Yes exactly that lmao
Wait did you just create that in like 1 minute
No I legit screenshot this when someone posted this code
you'd be surprised at just how common that is in this discord
Yeah I bet
You're right, that works! I'm new to it so yep, I'm using the default AIPath component (trying to get familiar with how it works).
Thank you very much!
no
okay
help please: ```cs
using UnityEngine;
using TM_Pro;
using UnityEngine.UI;
public class LobbyMenuManager : Monobehaviour
{
[SerializeField] private Level[] levelList;
void Update()
{
}
void DisplayLevels(Level[] level)
{
foreach(level i in Level[])
{
}
}
}
Syntax error, question expected
lol
oh yeah
Im trying to me a level select ui
and I have scriptable objects for each level
and I want to display the thumbnail and gamemode
ur loop is wrong
Mhm, there's still no question here
like hella wrong
my question is how do I accomplish this
But yeah you have some invalid syntax
use a for loop and you can match thumbnails list to the levels list
yeah
use the same i variable
make a list of thumbnails gameobjects , make a prefab of 1
then spawn them dynamically depending on the amount of levels array
yeah
and then change the color, thumbnail, title, gamemode, and description
Yeah you need to loop over your array, and for each level, create a new UI object prefab, set the title, the thumbnail. Might want to use UI wrap layouts to have auto-layout
There's 3 tasks here at least
start by making the prefab for the display of UI
so come back later
ok so start by creating the UI object class
First, prefab. As you're going to reuse the visual it's better to make it once and then Instantiate multiple times. On this prefab you'd have a script that you pass your title and image to it, and it takes care of placing them for you
🤤
eg:
public class LevelObjectUI : MonoBehaviour
no
why
public class LevelObjectUI : MonoBehaviour
this goes on your eventual Prefab
im doing scriptable objects
so you can access its method on instantiation
not monobehaviours
you're not listening
oooohhhhhhh
i see
yup
yup
i know what you mean
using UnityEngine;
using TM_Pro;
using UnityEngine.UI;
public class LevelObjectUI : Monobehaviour
{
}
: )
yes
what next : )
public class LevelObjectUI : MonoBehaviour
{
public string LevelName;
public TextMeshProUGUI uiText;
public OtherStuff stuff;
public void Init(string levelname, etcc){
LevelName = levelname;
uiText.text = LevelName;
etc.
}```
i dont get it
for (int i = 0; i < levels.Length; i++)
{
var instanceUI = Instantiate(LevelObjectUIPrefab, panelStackTranform)
InstanceUI.Init(levels[i].levelname, etc..)
etc..
}```
i dont know what goes in the etc
-_-
i'm just giving you example
ik
the logic of what to do should be obvious
you're in #archived-code-general not #💻┃code-beginner
