#archived-code-general
1 messages · Page 258 of 1
i see now why my RuleTile calls are so damn expensive
my special ruletile method checks a few maps for the actual logic. which only adds a little work.
but what ruletile does, is it looks through:
foreach tiling rule
foreach transform allowed by the symmetry
foreach neighbor position defined
Do work
so if you put 16 really specific rules that totally cover the space, and half of them use the rotation symmetry to check, and naturally this means a typical rule has 5 neighbor relationships defined…
That’s like 200 calls per one tile refresh. Wtf man
this is probably fine if you use tilemaps prebuilt in a scene, but not if you edit the tilemap dynamically in any way
in theory, by storing the results into an array on the SO, this only needs 8 calls instead of 200
ty for coming to my ted talk
I installed Cinematic Studio Unity and I can't add a sequence to the project. It just isn't there
CinematicStudio ? or you mean Cinemachine ?
this and this
oh you're talking about this
yea
then you should have these packages ye?
Cutscene można spotkać w większości gier, więc dlaczego nie wrzucić ich również do naszych projektów? Pokażę Ci jak możesz nakręcić te krótkie filmiki i uruchomić je w odpowiednim momencie w Unity.
Jak tworzyć animacje w Unity? 👉 https://youtu.be/RcJ7t7FJ3_w
Co to Unity HDRP? 👉 https://youtu.be/wEycDpfEtyA
👇 Dołącz do naszej społeczności:
...
not sure if im in the right spot here but I am having an issue with mirror, steamworks and unity. Can I ask questions about mirror, steam and unity here? or should I be posting elsewhere?
My specific issue is in utilizing the mirror 'Network Manager'. I am trying to have a menu where users can select to host online (thus using the default enabled fizzysteamworks transport on the network manager) or they can use LAN functionality via mirror (which swaps the transport on the network manager to a LAN transport).
I am able to do almost all of this correctly and thought I had it working previously, where the steam transport component gets disabled when going into LAN and the transport correctly gets set on the network manager, however I am running into an issue where the steam transport component is seemingly reenabling itself (or by something else I am unaware of) and the LAN now is appearing to be using the steam transport.
I know this is a long paragraph so let me know if I should be asking elsewhere. Thanks!
they probably moved it, check under Window if sequencer has its own thing now
To create a Master Sequence, select the + (plus) button at the top left of the Sequences window, then select Create Master Sequence.
btw this question belongs in #💻┃unity-talk . this is a code channel
i dont have it
do you have any compile errors right now
Oh my...
if so, they'll prevent any new packages from being imported
I said Window
talkin about me?
nah to @dull quarry
ok my issue might also end up needing to be there xD
yes but i gonna get it
now i have it
i need this time line
i`m so stupit in unity
I want to use a vector image (svg) as a button. I have already importet com.unity.vectorgraphics and now can put the image into the TextMeshPro button. The problem is it is transparant for some reason, does anyone know why?
you mean you assigned the sprite into the Image component's "sprite" field?
this is not a code problem, so you should ask it in #📲┃ui-ux . One thing I remember from using that vectorgraphics package was that the default importer mode didn't work properly in UI. I switched it to "Textured Sprite"
Maybe try that first.
Otherwise, go check in that channel
why do you keep asking this every day when the asnwer doesn't change
Sorry I didnt read the answer ...
ok so i cant add something there ?
no there is nothing that can be added there
Thanks a lot!
I've made a thread for it
I hope this feature will be added .. because I have the same problem with searching for users ..
yes exactly, its very limited for a faux Database
that was the reason for asking if I can add there data
idk what the last reply to the thread means by this
Edit: sounds like this is already possible! Thank you Unity team!
Yesterday, maybe it is possible, but the question will be hopw
the workaround to store "unique" info on each player would be using the Cloud Save
but you can't do anything search wise in the dashboard
Little annoyance, but when I open visual studio from the solution file, it doesn't seem to load all the dependencies correctly. Reopening it from Unity (by double clicking a script) fixes it all. I can't seem to figure out how to get this to work properly (sometimes I like to work in VS without unity open)
(these are in other asmdefs)
Is there a way to load two scenes, have them occupy the same space, but not interact? Or is there only one scene loaded, and only can use additive scene loading, then place them out of view range of each other?
huh, I'm not sure what I'd do about it missing some things
Depending on your definition of "interact", you could create multiple physics scenes
A physics scene (not to be confused with a unity scene) is a "world" in which physics happen
https://learn.unity.com/tutorial/multi-scene-physics talks about how to use them
I haven't really used 'em myself yet (but I might be doing that soon)
what kind of interaction are you trying to avoid
Yes:
- Physics scenes for physics interaction (or layer based collisions as a "lower tech" solution)
- Culling masks on cameras to only show one scene by layer
As for lighting, it's going to get sketchy
because environment lighting is based on which scene is "active"
trying to have two separate scenes is going to be a big challenge tbh
The Physics scene could be an option. I want to create two worlds and connect them via a Stargate like gateway. Just concern about managing two worlds in an active scene.
so many things would break
only if you naïvely try to rip a scene in half, really
I've had a pretty reasonable time with multi-scene workflows
yes but what are you concerned about specifically?
when you go through the stargate can you not just load a new scene?
all your singletons would have problems if any are in both scenes, or assume they control everything about their own little world
perhaps they want to keep the other half running
Stargate was a bad example since it's one-directional. I mean more like a "Portal" portal or maybe a "Transitionless" portal would be a better term.
in that case, it would be very annoying to keep both scenes' objects at the same place
you'd hear audio from World A in World B
now, that could be a really neat puzzle element...
that’s what I thought he was talking about
put the scenes in different places for sure. Use well trod "portal" rendering techniques to render the other scene through the portal
I'm going to be dealing with something similar soon, actually. If you've ever played Factorio's Factorissimo mod, I want to do that
i would first think long and hard about how crucial this is vs a loading screen + strong separation
also, portal will have a very different approach vs a hard stargate that actually loads a new zone
Hoping to do the transitionless because it's novel feature that isn't implemented allot, probably due to it's implementation overhead.
i’m just saying, before you spend at least 6 months on just this one feature, it should be really worth it
Found the problem. Pinned an old .sln file and at some point renamed the project without the space. 🤦♂️
whoopsie
and if your reason to implement it is that it is not normally implemented, then you are solely going to be wasting your time
like, your response tells me that you should absolutely not do this
implement what your game needs to be fun
(and don’t if it doesn’t)
i have a feeling he’s about to say something to the effect of “if I explain my specific scenario, you’ll understand”
Definitely all good advice. Working on a rough prototype using stuff from tutorials so far to try to gage if it would be any fun. Just trying to understand if i'm going down the right path for how I'd load world B into world A.
I say this as I spend another day implementing weirdly flexible UI systems instead of making my game fun
🙉
look, my settings menu uses the same UI prefabs as my scenario setup screen!
This particular idea uses the portal mechanic, so I'll probably try implementing a prototype and go from there.
Can you describe how you'll interact with these portals?
The basic way is you travel through from World A to World B. In World B you collect resources to bring back to World A. World A is the permanent world, World B is lost after the portal closes. Opening the portal again loads another procedurally generated world/place to collect more resources from.
and that sounds like a use case for a loading screen
It also means you're allowed to abuse the other worlds a fair bit
you are not using the portal mechanic in the gameplay itself.
You can put them in weird places (including on top of each other, since you're always just visiting a single other world)
You know, this reminds me of a game I made once for a jam
The theme was "Threshold". I made a game where you procedurally build a weapon by picking one upgrade per level
You kicked open a door and got flung into the new world
In that case, I just showed the new world's skybox on a material inside the doorframe
Post Prototype ideas include allowing NPC units to travel between world A and world B. Perhaps have a rail system that can go through the portal, or create other portals directly from a location in world B to a depot in world A.
and hijacked your input for a few seconds as you flew into it and the new level appeared
This would be insufficient if you wanted to interact through the portal, but that might not be necessary.
Yeah I'm just wondering how to implement loading two worlds in what would be essentially a open-world. Having World A at 0,0 and then creating another world at 10k,0,0 seems straight forward enough. Can use game mechanics or hard boundaries to prevent player from wondering too far from the World A. Only concern with that route is around if there are any weirdness that comes with having high values in the coords of gameobject.
You might start to see float weirdness at 10k so I wouldn't go that far away. Since your 'worlds' don't actually need to physically connect, you can have them pretty close to each other (level design permitting)i in the scene. I would think of it as one world with two 'realities' and keep them near the origin and just think of each as an isolated unit
if you really want them to be more their own 'world', you could have each be its own scene and load/unload them as needed, but if you want the player to be able to see through the portals you'll need both loaded at the same time anyway, so you may as well load it all
Thanks for the info, I'll avoid the ultra large offsets. I'll aim for something smaller but manageable.
I think I just need to bite the bullet now, turns out RefreshTile already does a cacheing thing
for reference, setting the tiles is 1/15 the cost
...Should you be refreshing all the tiles 17 times?
Or are there that many tilemaps
there are that many tilemaps
in this case, only 741 actual rule tiles getting refreshed
the vast majority of cost is on evaluating a given ruletile
For reference, the reason I have 17 tilemaps is because separate collider properties absolutely must be separated, which is a bummer
4 of those just have platform effectors in different directions.
3 solely exist to have a different collision layer
Guys if I have a player Green and enemies Red; and an attack that shoots automatically at set intervals in an area Blue; how can detect where the Blue attack should aim for it to hit the most enemies (or at least a good chunk of them)? Should I have like several posible set positions where it can land and check all of them individually to get the one with the most enemies nearby or...?
Like I want it to automatically check for large groups of nearby enemies
best way is probably influence maps of some kind?
http://www.gameaipro.com/GameAIPro2/GameAIPro2_Chapter30_Modular_Tactical_Influence_Maps.pdf
does anyone know how i can get world bounds of a ui element?
If both the attack and the enemies are circles or spheres, then you can simplify this to covering as many points as possible.
This is a tough problem to solve exactly.
Just randomly trying points near a random enemy will work decently.
yeah that's true
you also could maybe divide the world into cells of a size and keep track of which ones are densest?
that works best if the map is more constrained though i'd guess
I have look it up a bit, and seems really interesting, but no idea of how to actually implement it
Is the blue radius fixed? (I assume yes)
yeah, as far as i know it's not really a problem with a trivial answer
They are not neceserally circles, most of them are basic shapes and even though the game is 3D I am only moving in the Z and X axis
if it's not important to solve it very well, just picking random enemies and seeing how many are around them until you find a decent one like Fen said is probably fine
An exact solution is probably going to be be too expensive.
smells like a NP-hard problem to me
i'd start by just calculating how many enemies would be hit if you shot directly at every enemy in range, then picking the best shot
But approximating it in 2D will be easy enough.
This is what I'd expect the attack to do, as a player
that's why influence maps are a good approach imo, but yeah they not trivial to implement for everyone
I wound up implementing this kind of thing for an RTS AI
yeah, unless you have a ton of enemies i'd start there too
right, for large numbers it feels worth it
Each point of interest was converted into a gaussian function centered on the point
and then I did gradient ascent in some Bursted code to find a high point
I got a somewhat approximate solution which is to have a bunch of "template colliders" moving around the scene and every frame send a back how many instances of enemies they are hitting and chose the one with the highest count as the optimal target
Seems kinda messy for a just a approximate solution though
But I see a precise one is even more complex
I could also have each enemy have a recount of nearby enemies, and chose the enemies which have the most enemies nearby and hope to hit them
Which of these approximations do you see more appropiate?
neither, i would do this
your 'template colliders' are basically that, just it's smarter to use the enemies themselves as those 'templates' since you know each enemy contains at least themself in their radius
https://i.imgur.com/5zIr8S1.mp4
Can someone help me figure out why this buoyancy code is making the rigidbody stop floating up before hitting the peak of the 'water' plane?
Buoyancy script: https://pastebin.com/uL9fSwxU
It's a raycast buoyancy system. It's shooting a ray up from the GameObject it's attached to.
Where the raycast hits the 'water' plane, a "cursor" (green sphere) is shown on the plane. That's supposed to be where the GameObject floats to.
Instead, the GameObject floats upward but never tries to reach the peak of the wave (see mp4 showing this in action) despite the "cursor" (green sphere) hitting that point. Any ideas what might be going wrong in the floating logic?
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 debugging steps have you taken?
Have you tried adding logs to make sure the force is being added when you expect it to be?
Also why AddForceAtPosition instead of just regular AddForce?
Yes!! Changing the point from which it floats from fixes it! thank you, that makes sense! as for why it is set up like AddForceAtPosition, honestly it's from a tutorial I found. I'll experiment with AddForce instead and see what works better. thanks!
out of curiosity, when you say debugging steps, what approaches do you mean? I had changed the code around and added that cursor functionality to show where the ray was hitting. do you mean steps like that or something more specific?
They mean adding Debug.Logs as well as using the Debugger and adding breakpoints
All right, got it for future use then, thanks.
The Debug class also has helpful methods like DrawRay so you can visually see where your raycasts are going btw.
Lots of tools available.
how can typeof(object).Assembly.Location and typeof(UnityEngine.Object).Assembly.Location produce incorrect assembly locations ?
Wdym by incorrect?@frosty snow
because object and UnityEngine.Object are 2 very different things
Hi guys, I'm noticing some weird behavior with transform.SetParent(x) when using high velocity rigidbodies.
Are there any red flags when setting the parent of a rigidbody GameObject?
What weird behaviour? In general the idea of moving parent and rb child is not a good idea
I spawn a high velocity projectile, and on impact I create a parent, then make the projectile part of the parent as it becomes new "terrain"
This isn't code related. The channel is a code channel, maybe try moving your message (delete/repost) to #💻┃unity-talk
I've noticed this is triggered if rigidbody.useGravity = true is set
This is too vague for me. You still havent said what the actual issue is.
Don't worry about it -- I think this is just one of those things I need to RTFM or trial/error
while in editor mode, can I get a variable from an object in a scene that isnt loaded ?
@round violet Nope, but you can load the object and set active to false!
Absolutely not
Save the variable in https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
its for editor purposes
saving time
I looked through the docs and it doesnt looks like i can get a Scene struct from a scene that isnt loaded
can you not do that using AssetDataBase ?
that gives you a SceneAsset instead right
i only looked in SceneManager, i didn't knew they was a editor version of it, ty
but regarding my original question, this isnt what i need.
This open a scene, my goal is to "fake open" a scene so i can get the root objects
or maybe i dont need to "open" at all, but i dont know how to get data from a scene that isnt loaded
Open->Get Objects->Unload
So i have many objects in my scene and i would like a GameManager listen to i guess an event coming from the objects in the scene, how do i do this?
wjat's the easiest way to check which area my enemy navmesh is currently walking on?
would it be sample position or smth
so you want to know which of these areas you're currently in?
NavMeshHit includes a mask field
which tells you which area you hit
Slightly unclear on how you actually interpret that. I guess it's a bitmask like a LayerMask
can just use << right?
i would have to test myself to figure out if its just straigt up ints or bitmask, but to test if something is in a area would be something like
(value & area) != 0
value would come from the NavMeshHit area would be the one or multiple you want to test for, so this statement would be true if value contains any bits from area
when calling EditorApplication.EnterPlaymode(), the rest of my code wont be executed
how can I tell Unity to continue the execution flow after the EditorApplication.EnterPlaymode() ?
e.i:
EditorApplication.EnterPlaymode();
Debug.Log("Executed"); // this doesnt get called
EDIT :
Debug.Log("Executed"); will be executed, but when entering playmode some stuff seems "cleared", like coroutines
something like this?
if (!NavMesh.SamplePosition(transform.position, out _enemyNavHit, 1.0f, wallrunLayers)) return;
if ((_enemyNavHit.mask & wallrunLayers) != 0)
{
Debug.Log("on wall");
}
wait no I did it wrong
it might work, i was making some assumptions of what the mask actaully is, so i would first start off by logging what mask actually is, and see if it lines up with values from your layers
either directly or 1 << n versions
looks like navmesh has a few things on it like GetAreaFromName that will be helpful for getting the mask for a named area
got it working
private void CheckIfOnWalls()
{
if (!NavMesh.SamplePosition(transform.position, out _enemyNavHit, 1.0f, wallRunAreas)) return;
if ((_enemyNavHit.mask == wallRunAreas))
{
Debug.Log("on wall");
}
}
wow hate the naming then, so they call it mask, but its not a bit mask
That seems off. Even if it isn't a bitmask...
if ((_enemyNavHit.mask & wallrunLayers) != 0)
This would still succeed
yeah it would since bits would be 100% identical in that case
are running coroutines started in editor cleared when entering playmode ?
good question. i've never used editor coroutines before..
ah guess the GetAreaFromName just returns the index but not the value of the layer then
because when entering playmode then starting a coroutine it get "stoped" afterwards
Yes, that's correct.
so would need to do 1 << navmesh.GetAreaFromName()
also, terrifying. i hit F12 to look at the implementation
to get its value
it uses a fixed block
ugh
it's passing a Span into native code
what did you go to def on to see that
GetAreaFromName just goes to a static extern for me
if i had to guess entering playmode is causing a domain reload
prob this
but i am not reloading domain on enter play mode
i disabled it in editor settings
I must have VSCode set up to try and decompile
could you fake it, and just have some initlizeOnLoad logic take over after after entering play mode
so i dont know why HandleBackgroundGeneration doesnt keep ecxecuting after starting play
[Button("Start Background Generation")]
private void StartBackgroundGeneration()
{
if (!EditorApplication.isPlaying)
{
EditorApplication.EnterPlaymode();
}
StartCoroutine(HandleBackgroundGeneration());
}
hmm odd, could be version too i guess,
i could do this, but the point of my inital goal is to make it easier not adding to much code xD
how do i make the npc make a new path that avoids all objects, currently it just keeps on the original path that hugs the object so the npc trying to get to the point but gets stuck on the objects https://gdl.space/nipezosuqo.cs
what could cause thes hughe lag spikes from the editor loop ?
it’s basically editor-specific code
I find several gameobjects I have lead to high editor usage when they are visible in inspector
so first thing to do is see if this only happens when a specific thing is visible in inspector
if so, then it is likely some editor script running on one of its components
hey, does unity have some functions to trace against an infinite plane on an axis? ie not actual gameobject with collisions, just an infinite plane, and return the position
could any build in script cause this ? cause i never made a script that runs in the editor in this project
what do you mean by “trace”
it does has a class called plane you can raycast agaisnt
yeah but you get my point
I have a starting position and direction for a ray, a position and face direction for the plane, and I wanna know the point where the ray intersects with the plane
yeah that might do it, thanks
oh cool, they already made a data structure for ot
@ruby elk look at what i linked its exactly that
oh, yeah. then use Plane.Raycast
it’s in the link
thank you
fyi in Unity, Raycast usually specifically means a query on the physics system
not always, cases like this where its for the one object that might only exist in code
also the collider types have similar methods on them if you want to cast only agaisnt them and not world objects
idk. this looks like it might only happen on fixed frames
looks like garbage collection kicking in, does this happen only in editor or also in builds?
also are you instantiating lots of objects and destroying them
it appeared out of nowhere and its only a problem in the editor so im gonna hope it dissapears just like it suddenly appeared
i mean that Casting in unity usually has the connotation of specifically referring to the many physics queries, which produce RaycastHit
yes, quite a lot actually
lemem test smth
well shit
that is the cause then, good chance it can be mitigated quite a bit by using object pooling
you can’t instance and destroy tons of objects every few frames, bro. That will bring your game to its knees
and reusing objects instead of fully destroying them to just make a instance again later
object pools are pretty simple to make, also unity 2022 has built in tools for it
it worked 5 minuites ago
in your case, you need to make a pool
This could be because you've got the hierarchy or inspector open while playing.
Especially if the behavior just appeared out of nowhere
yeah. You’re lucky the inspector is the only thing yelling at you right now
I would also smack the editor with a restart and see if anything changes
ill do that
I'm pretty sure I've seen cases where EditorLoop wound up including my own code, though
maybe it was including the time taken to render the game view?
Make sure you actually profile a Development Build, so you don't have the editor lagging out your profile results.
imho editor profiles are nearly useless
i do mostly full instance and destruction because my game does it all at once, and then in small bits at a time. Which is fine.
I will later upgrade to a pool system.
you're creating 11KB of garbage per frame, which could definitely be making the garbage collector run at regular intervals
that ~might~ show up in EditorLoop
the builds should work fine tho, the thing that takes up the most is the editor loop. that doesnt run in builds am i right ?
in this case, the built game would also run poorly
ill check that
Yeah, that's my whole point
the problem is i cant work with 15fps in the editor and i cant make a build everytime i want to try smth
in my case, all my scripts have very limitted use of Destroy, and all reference one specific monobehaviour (spawned entity handler) to ask it for “destruction.” This way, I can later refactor by having that one behaviour instead ask to go to a pool.
have you restarted the editor yet
its starting
Hello, I am new to untiy and I want to learn first person movement, is using character controller better or a rigidbody? also can u suggest a good tutorial to start? I also want animations as I have a model ready in blender. Can someone pls help??
if i hide the garbage collector it still shows the lag spikes
you can switch the profiler to target the editor, not the player
that may reveal something
untoggle the Record button to make the graph stop, btw
it starts spiking when i spawn my bullet impact effects but it doesnt stop even if all of the particle systems have been destroyed
pausing the game won't stop the editor, so it'll keep flying past
Sounds like you have something getting stuck.
maybe you're continuing to spawn objects
not sure where to ask this but
is there any difference between the update order in a game’s build vs running it in the editor?
specifically in regards to drawing
its best not to rely on the update ordering
there are ways to define it, but getting into that will make life pretty complicated
this is why we have both Awake and Start and Update and LateUpdate
Can you be more specific here?
Are you asking about script update order or something with rendering?
script update order
im trying to update a shader param before something draws and it works in the editor player but not when i build
should be fine, Update is long before any rendering
https://docs.unity3d.com/Manual/ExecutionOrder.html
this graph in here shows the order all the unity messages get invoked in
is there a writeup somewhere on the internal logic of the functions in HandleUtility? especially this one https://docs.unity3d.com/ScriptReference/HandleUtility.CalcLineTranslation.html
I'm trying to recreate the transform gizmo for runtime usage
I think that's specific for the editor. Could consider looking into this:
https://docs.unity3d.com/ScriptReference/GL.html
it being editor only is why I'm trying to recreate them, sorry if I wasn't clear
regardless, GL works at editor too
I don't need the rendering stuff, rather the "mapping a screen relative movement to a world space movement constrained to an axis" stuff
Sounds like an application for Vector3.Project
Given the handle's world-space direction, convert that to screenspace and throw out the Z component
Project the mouse position onto this vector.
..actually, maybe don't throw out the Z component, since you'll need to convert the projected mouse position back into world-space afterwards
I haven't implemented this exact thing before, so I'm a little fuzzy!
https://gdl.space/xojepigiwe.cs can anyone tell me why my rotation feels buggy and freeze? in void LookRot()
you are mixing transform and rigidbody, dont do that. iirc you've already been told this
Hi, i'm making an online game using relay and netcode. I need the player to send their username to the server when they join, to do this i have a function subscribed to the OnClientConnectedCallback action. This function should send a ClientRPC to the client that just joined, and that will trigger sending the username back to the server, but i cannot get it to work where it only sends to one client. The code works when i do not include clientRPCParams, but obviously sends to every client not just the client that joined. The error message says that the RPC is called on a network object that is not in the spawned objects list
Is there seems to be any problem with this script? It is printing not grounded constantly although the character is grounded
How can I rotate the body without using transform then?
OOO tysm
Anyone has any improvement/optimization recommendation for this StateMachine and State code?
https://paste.ofcode.org/cWEZtzi6cpg6BfcdQfTHpf
https://paste.ofcode.org/EgtfQxwGZ5XgsKPyicntpA
Theres a lot heres thats pretty unusual, if it fits your needs though then theres no need to really change it. I'll point out some things that arent a good sign but "improving" it would pretty much be an entire rewrite.
In your design, the states need to know about the state machine. This seems to just be for the purpose of GetComponent. This is giving your states too much information.
Doesnt make a lot of sense to me why the statemachine is a mono and why the states arent.
Add a Exit for your states so they can clean up stuff if needed.
The handle, fixedhandle, and late handle smells like overengineering if you arent actually using all of them. I'm unsure of what you would ever need all 3 for.
I have several "tick" methods on my state machine's states
What would you even use them for? I cant imagine a scenario really where an object can exist in a state where it needs to update in update, fixedupdate, or lateupdate
Although, I'm lying a bit -- these are on my "modules", which are basically just components that I manually call methods on, rather than letting Unity do it
Tick runs in Update, duh.
FixedTick runs in FixedUpdate and is used for systems that need to affect physics
IKTick runs after all of my IK systems are finished solving, and is used for things like positioning the camera correctly
I have LateTick on here, but it's used by nothing
I'm using FinalIK, which updates deep into LateUpdate.
Thanks. I think I am removing StateMachine from State and remove unnecessary public function calls from StateMachine, but I have lots of things to do with Update(), FixedUpdate() and LateUpdate()
How come you cant manipulate dictionarys while iterating over them but you can in other languages
you can it just depends on how you do it
Newer versions of .NET allow you to set values while iterating over a dictionary, actually.
alas, not for us!
Hello! I want to find to position of the top part of an object. What im trying to do is that I have two quiz files since im making a quiz player and I want to start looping the items from the top. Heres a screenshot of what it is currently doing: (i just set it to the position of the object i want to find the top part, which results in just looping from the half 😢 )
forgot the screenshot, sorry
I don't understand what you're actually trying to accomplish
first sentence
that gives the center
Ah, I see.
i want the top
this is gui so probably as rect transform?
how?
(transform as RectTransform) will cast your Transform to a RectTransform
i have that object as a recttransform variable already
It looks like you want to use https://docs.unity3d.com/ScriptReference/RectTransform-rect.html
The rect is in local space, so you'd need to transform it to world space to get the correct size
alright
hmm, I'm not sure exactly how to do this, though
You know, an easy option would be to parent an empty object to your button
and just get its position
recttransform.rect is the world space position?
wait
i could just set position of an invisible object at the top of the list
and i dont need to do casts and all that stuff
alright works!
Hi I can't turn horizontally does anyone know what the problem could be?
how we supposed to know anything without seeing the script/setup ?
🔮
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class FPSController : MonoBehaviour
{
public Camera playerCamera;
public float walkSpeed = 6f;
public float runSpeed = 12f;
public float jumpPower = 7f;
public float gravity = 10f;
public float lookSpeed = 2f;
public float lookXLimit = 45f;
Vector3 moveDirection = Vector3.zero;
float rotationX = 0;
public bool canMove = true;
CharacterController characterController;
void Start()
{
characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
#region Handles Movment
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
// Press Left Shift to run
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
float movementDirectionY = moveDirection.y;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);
#endregion
#region Handles Rotation
characterController.Move(moveDirection * Time.deltaTime);
if (canMove)
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
#endregion
}
}`
Don't recall if CC prohibits Transform operations with rotation 
rotations should fine iirc
start debugging
There are two rotations being applied. One to camera and the other to this object. I'm assuming the camera has got the unwanted behavior (mouse y)
guys i need help setting a 2d outline for a sprite,when i drag the material onto the GameObject it just disappears because of "Material does not have a _MainTex texture property" even tho in the shader graph i set the reference to "_MainTex"
Maybe canMove is false?
welcome to URP hates sprite shaders
Well, SRP in general
No, cause movement and jumping works
Which object isn't rotating correctly?
The camera or the character body?
the camera
Well, the camera is only assigning changes to the x-axiscs playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
and is camera child of player?
yes
I can't turn horizontally
The camera only rotates on the x-axis
Check out #archived-shaders, but if you're using the shader graph usually that's more friendly. Make sure you're using 2D texture node as well
(assuming) if child of character , its pretty normal to rotate player body to get camera to rotate on Y as well
i'll check out the shader channel
what was it
I've seen sprite stuff done in shader graph so I'd expect it to be possible, but HLSL is a nightmare for sprite stuff
linked the script to camera instead of the player object
how do you convert a direction to screen space? just camera.worldtoscreenpoint then normalize it?
also I could keep the Z component but it'd become invalidated by the project
who would you normalize it
also WorldToScreenPoint will not convert a direction just a point
vector3.project takes a normalized direction iirc
How do i add a AssestPostProcessor to a obejct i imported so i can add a script into that prefab?
the asset post process runs everytime things of certain types are imported
what kinda asset is it?
https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessModel.html
for example here is one that acts on model import
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
can you interact with button elements when the displaystyle is .none ?
Hey gang, I'm using a UI image (SelectionRect in the code) to accomplish RTS style box selection (drag mouse over multiple Units to select all at once):
private void CalculateDragBoxCollisions() {
Vector3[] positions = new Vector3[4];
Vector3[] corners = new Vector3[4];
// Use the UI rect to get the world corners
SelectionRect.GetWorldCorners(corners);
// Raycast at each corner and get position
for (int i = 0; i < corners.Length; i++) {
Ray = Player.Cam.ScreenPointToRay(corners[i]);
if (Physics.Raycast(Ray, out Hit, raycastMaxDistance, Player.GroundLayer)) {
positions[i] = Hit.point;
}
}
// Find the minimum and maximum extents
Vector3 min = positions[0];
Vector3 max = positions[0];
for (int i = 1; i < positions.Length; i++) {
min = Vector3.Min(min, positions[i]);
max = Vector3.Max(max, positions[i]);
}
// Calculate the center and half extents for the overlap box
Vector3 center = (min + max) / 2f;
Vector3 halfExtents = (max - min) / 2f;
// Query overlapping colliders
Collider[] colliders = Physics.OverlapBox(center, halfExtents, Quaternion.identity, Player.SelectableLayer);
// Do stuff with colliders
}
This code works great until the Units I'm mousing over are near the edges of the screen. The closer they are to the center of my camera the more accurate the collisions will be. The further from the center the more likely the collision will occur. I found this has to do with the fact that my Camera (Player.Cam) has an X rotation of 55. If I set this value to 90, so the Camera is looking straight down towards the world (3d world, cam is perspective), then everything works as intended. My question: How can I adjust this code to simulate this 90 degree rotation? I was hoping to avoid using another Camera. Thanks!
I've been trying to make a modular pie chart / roulette wheel generator. I have made multiple iterations and none of them have worked, im ashamed to even show em - they dont work at all. The idea I had is that I have a number "spaceLeft", I instantiate a set amount of slices and assign them a portion of the space left. They are then rotated so that the start of the slicing starts where the previous slice ended, and the fill amount is set to the assigned space, and then the next slice is instantiated and rotated accordingly. So far the slices overlap and never reach 100% (sometimes seemingly more, sometimes less), anyone know a simple way I could do it?
So is it your logic that's having a problem or is it the component you're using that you're not understanding? Either way, post code.
well the current version looks like this and is awful in every way
{
for(int i = 0; i < numberOfTiles; i++)
{
CreateNewSlice(i);
}
}
void CreateNewSlice(int index)
{
GameObject temp = Instantiate(wheelSlice, wheelOriginPosition.position, Quaternion.identity);
int sliceSize = 0;
if (index < numberOfTiles - 1)
sliceSize = Random.Range(Mathf.RoundToInt(360f / (numberOfTiles * 3)), spaceLeft);
else
sliceSize = spaceLeft;
tileList.Add(temp);
temp.GetComponent<Image>().color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
temp.GetComponent<Image>().fillAmount = 1 - (float)sliceSize / 360f;
temp.transform.rotation = new Quaternion(0, 0, spaceLeft, 0);
tileList.Add(temp);
temp.transform.SetParent(wheelObject.transform, true);
spaceLeft -= sliceSize;
}
Is this on the UI? You've got tools like Radial fill if you want to use that
or is that what you're using here. I think there's specific sprite masks for it too but I can't recall them
yeee it's on the ui and im trying to set its fill amount to correspond to its size
so i can use radial fill instead of fillamount?
i mean that would make it more compatible with the rotation aspect at least
as for layering problems, what is rendered on top is dependent where it is on the hierarchy
i googled and maybe range start / range end sprite masks?
well i dont want them to be on top of each other in the first place, that's why the idea is that they are rotated to the start is where the previous one ended 🤔
does anyone remember what this type of notation/formatting is called? I want to set VS to format this way, or at least stop 'correcting' me
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
playerRb.AddForce(Vector3.up * 500); } }
and then the fill amount corresponds to how big it should be
Ah, yeah that's probably doable then. Just continue where the last fill left off.
exactly, but it just doesnt seem to work out for me hmmm, but maybe it would work better if i swtich over to radial fill like you said, ill try that
tyty
Never seen that before. It's not pretty and not the standard C# formatting conventions.
But you can edit the formatting settings in Visual Studio options, under the "C#" item.
yeah not a big fan of k&r
It is funny that they are using it as standard in the beginner course
Overview: The goal of this lesson is to set up the basic gameplay for this prototype. We will start by creating a new project and importing the starter files. Next we will choose a beautiful background and a character for the player to control, and allow that character to jump with a tap of the spacebar. We will also choose an obstacle for the ...
lots of java and c++ coders do it
It's not even K&R is it? The closing braces are on their own line no?
and js
oh yeah the end one is so weird thing
thought they meant the opening
But know that Unity isn't the reference for code style
I am not a fan of the closing bracket there. i prefer it on the next line
Not my preference, especially on something like Update
m_ 😔
Properties in camelCase, and the Geneva-convention-breaking stuff in Unity.Mathematics am I right
I love their excuse on the home page "in C# int and float are built-in types, so we made our own" - no, they're aliases of built-in types
Keywords
I haven't done a deep dive yet, but off the top of anyone's head is there a way to quickly derive an efficient cluster formation for a number of spheres? Like rather than just glueing to each other on contact, I'd like them to do their best to keep a spherical shape when they are connected.
sounds like something from one of those neat algorithm web pages but unfortunately I don't bookmark them
Yeah I'll have to do some digging around.
I optimized the algorithm for ruletiles
it now saves a lookup table
It dramatically improved performance
right now, my smallish map was spending like 300-500 ms to refresh all tiles. it's now 100ms
only important because I expect the scale to increase dramatically
and spending 3 seconds refreshing tiles is dogshit
Hey all. I am having troubles with too many AssemblyDefinitions. main issue is I am having to reference different assemblies over and over(like Unity.Logging/Unity.Burst/Unity.Collections).
If I put an assembly in a sub folder of another assembly do I get all it's references, or if I reference another assembly will I get all it's references?
Or is there a way to add references by default for all assemblies?
why are you using asmdef in the first place
Like are you asking me what are the advantages of them? Inwhich case I would say google it
Or like in my case why, inwhich case I would say google the reasons why to use them
no i mean why are you using thm in the first place
Google the reasons why to use them
i know what they are and what they're for..
Okay, now back to my question then?
I tried "Auto Reference" but my other assemblies I still have to assign the reference. Not sure what the docs mean by "Predefined Assemblies" will renference them
And at that I can't Auto Reference stuff like Unity.Logging
my UI slider wants me to pass predetermined value instead of passing its value on change, how can I make it pass its value? it worked in past so idk what's happening.
Predefined are the ones from unity
you need to select the Dynamic function
thx
but it doesnt show me that option here idk
more likely the signature doesn't match
try float
yup its a float
Do OnMouseDown and similar methods affect only the first collider it touches?
Looks like it
Might as well just raycast
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IPointerClickHandler.html
This can be an alternative to MouseDown (for UI specifically but I believe it can still work on gameobjects otherwise if they have colliders*)
My real question is, what is the most versatile and effective way to detect mouse clicks/hovers and touch inputs
2D Raycasts?
Lot of the unity tutorials are mostly 3D raycasting but they are similar
Gotta use the Physics2D type
may need to read up on layer masks and how you resolve the layers you want since that's a concept of its own
Great. Appreciate the info
what is good practice for organizing class data in unity?
if i were to make something like a dungeon crawler with variable enemies?
Stick to composition approach and don't derive classes too deep
what class data, like the different stats an enemy can have?
something like that
i usually use SO to plug in the data, and then at least it lives somewhere visible instead of hidden away in some file. And better than relying on the data being saved on prefabs
aren't all objects scriptable?
it's the alternative to populating data with JSON
for data defaults and it has editor support
it's the name of the utility class
we're referring to the specific unity Scriptable Objects, where you can create an instance of something that'll happily live inside your assets folder
is there a way to make a UI Document invisible by default instead of making it invisible in a script
If i set it to displaystyle none for each individual component i cant set it back to normal in a script as a whole
So Currently i just leave it as visible then set displaystyle to none in awake
ive been thinking about it but i have only made few actual games so i think ill simplify things to help learn unity
and then revisit this when i have more experience
scriptable objects are very easy, nothing to learn even. After using them you may think "is that all this is for?" because theres really not much to it
if you say so ill do some research
more than mandatory if you're doing something like a dungeon crawler
otherwise you can do it the old fashion way and use JSON / plain text and type out the addresses for all your reusable assets (rather, you'd assign by ID this way and have a asset database lookup)
You could use csv! 😸 (and even convert that to SOs dynamically if you want)
ive seen what they could do; is it possible to make constructions in scriptable objects?
what about making inheritances?
You usually couple them with your prefabs such that if you had an Enemy Gameobject with an EnemyStats script, your scriptableobject will define what sprite you'd use and health totals of this creature.
Meaning you can use a single prefab to define what an Enemy is for all your scriptable objects
Which goes back to my previous message about sticking to a composition approach where you're less likely to run into type issues from inheritance
public class Entity : Monobehaviour
{
private float health;
private float mana;
}
public class Enemy : Entity
{
public enum EnemyType
{
Melee,
Archer,
Magic,
Assasin,
Hunter,
Rogue,
Priest,
//ect
}
private EnemySO enemySO;
private Dictionary<EnemyType, EnemyBehaviour> behaviourType;
//Enemy AI movement and actions
private EnemyBehaviour behaviour;
public void Assign(EnemySO enemySO)
{
this.enemySO = enemySO;
behaviour = behaviorType[enemySO.enemyType];
health = enemySO.health;
}
public void Attack();
public void TakeDamage();
public void Path();
}
public class EntitySO : ScriptableObject
{
[SerializeField] float health;
public float Health => health;
}
public class EnemySO : EntitySO
{
[SerializeField] EnemyType enemyType;
public EnemyType EnemyType => enemyType;
}
some ideas
and some bad ideas:
public class Entity : Monobehaviour { }
public class Enemy : Entity { }
public class MeleeEnemy : Enemy { }
public class ArcherEnemy : Enemy { }
public class HunterEnemy : Enemy { }
public class MagicEnemy : Enemy { }
public class MeleeHunterEnemy : Enemy { }
public class MagicArcherEnemy : Enemy { }```
It's not so much bad, but less expendable when later on you're like, maybe you want some AI to be both an Melee and an Archer, well in the top implementation you'd allow for multiple assignment and blend your logic together.
Yet by doing inheritance this way you've kind of bound their behavior by these derived classes making it quite difficult to improve or mix it up later on.
this is a little overwhelming 😅
i think i can follow
Well, beyond the implementation, that's the idea of scriptable objects
for general usage
pair it up with a prefab
many scriptable objects to 1 prefab
oh yeah totally
treat it as the blue prints for which each enemy should at least have
i would add an attack value but im not sure how well that would work if i were to make special enemies with specific attacks/ patterns
like how a damage over time poison effect would work
Starting out though you'd want to try to keep your ScriptableObjects immutable, so keep your fields private and slap on SerializeField so you can still edit them in the editor
but allow for public getters just to read the data without allowing them to be edited
you can consider this as other components you can slap on the EnemySO much like the EnemyBehaviour class declared on mine there. (well, only declared a field, but it's delcared on EnemySO as if it were a component)
Like an Effects class and each EnemySO can take a list of Effects they can apply
what is scriptable object inheritance need for exactly?
keep it structured much like the business logic (prefab) side
EntitySO -> EnemySO
Entity -> Enemy
Every entity has health, every entity has a movement speed
so our derived enemy too will have to include those variables
Now, Entity -> Player would be similar such that you as the player has health and a speed
You may or may not have multiple SOs for the Player, but if you were to allow different starting classes and such then you would
The overall idea of setting it up this way allows you to pump out different profiles of enemies/items/classes, ect pretty quickly on the editor
BatEnemy => 30 health, Melee Enemy, BatSprite
OrcEnemy => 60 health, Hunter + Melee Enemy, OrcSprite
I've been setting up inheritance chains
that's the idea. Enums you can eventually just throw in namespaces
also, Unity Editor doesn't like multiple non-nested classes that derive from monobehaviour or scriptable object on the same script
it's ambiguous to the editor when you drag script assets around on it
(are you trying to drag Enemy on this field or Player?)
elaborate? my lingo is not there yet
i was planning on making separate gameobjects that inherit form this script
or something like that
you want to keep your classes in separate scripts because when you bind references on the editor it won't know what object it is to create
sometimes it may seem obvious what the editor should do, but it's dumb and won't figure it out without you clarifying it by keeping it separate
even if i specify a class separate from the others?
Yes. Unity expects one class inheriting a unity Object in one file. Putting more in the same file risks problems.
so i should only include a entity class?
I forget the full details but you'll encounter weirdness from the editor if you do. Maybe it just yells at you, I forget.
1 class per script, even if it's smallll
nested classes are fine though
apparently it would be a good idea to use [CreateAssetMenu]
Youll need those for your ScriptableObjects
trying to make it so that these private values can be changed, however it dosen't seem to be working
You'd access them via these properties. Funny though you got the naming convention upside down.
Underscores are usually used for private fields, while properties use Pascal case.
anyone know how to fix the issue where Unity automatically turn on "Collaboration"?
it causes the "[Collab] Collab service is deprecated and has been replaced with PlasticSCM" issue, I have tried turning it off in the ProjectSetting.asset, however whenever I open the Unity, it turns it on again after compiling.
Maybe get/update the version control package and try again
when I open the project, it loads this message, then it turn the collaboration on again.
Did you update the package?
yes.
Take a screenshot of project settings - services
not sure what do you meant for "project settings - services", like this?
@latent latch if your still on could you help me get some very broken code working
There should be "services" category in your project settings window.
How would you handle interaction in two instances: A wooden chest/fire pit (foot height) and door/floating object (chest height).
Would you have two raycasts? Boxcast? Angled raycast from highest point to floor? I'm trying to figure out the most performant. It seems running two raycasts (chest and foot) may be the best option?
Ah, I see. You're using 2019.
2019 is long unsupported. I recommend updating your editor.
I usually do some area check, like a trigger collider or overlapsphere, along with a shape cast like spherecast.
Since i do it using where the player is looking, where the object doesn't matter too much. They look down to target the chest or firepit, or they look up to target the floating object. Just one cast
Raycasts are almost free though. So super cheap. Play around and do the two cast method if you want
Speaking of raycasts,
I want to send a raycast through a circle that's displaced to the side in a 3rd person game
Would I want to use Camera.WorldToScreenPoint then ScreenPointToRay to get the direction?
Well, iirc, world to screen point gets a scene coordinate, and does maths and converts it to a vector2. Screenpoint to ray gets that vector2 and draws a ray on the cameras forward direction
Its not the same as forward direction on perspective camera
Are you talking about a gun or something?
Ah very nice
Its for aiming spells in my game,
while button is held it makes some floaty shapes that you aim through
They arent centered on the screen though, its branching off of player and moves around a bit, still a billboard though
I see
excuse me, is it possible to grab every PlayableBehavior from PlayableAsset/PlayableDirector?
I can't found any way to do that.
MainCamera is not moving smoothly even when MoveTowards, why?
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.
Hi everyone.
this is my sample code.
https://gdl.space/guzoviwaqe.cs
how do i get the highest Time?
i know Mathf.Max but how do i use in this case?
in the last argument of MoveToward. if you multiply your cameraSpeed with deltaTime cameraSpeed*Time.deltaTime and reduce the speed. will it go smoother? It should move linearly.
obligatory: use cinemachine
but you also want to update your camera in LateUpdate rather than Update because you want it to update after the player updates
No, it will not go smoother and cameraSpeed is 0.1f right now
Maybe if I use cinemachine it may work, thank you guys! I will try that
You're not really using MoveTowards correctly
Is this possible? I'm trying to assign a function inside that uses the value returned from the event.
{
if(variable == value){
}
else{
}
}```
_resourceHandler.OnHealthChangeSet += () => _ui.ModifyHealth(_resourceHandler.CurrentHealth, _resourceHandler.MaxHealth, HealthModifyType.None);
_resourceHandler.OnHealthChangeHurt += () => _ui.ModifyHealth(_resourceHandler.CurrentHealth, _resourceHandler.MaxHealth, HealthModifyType.Hurt);
_resourceHandler.OnHealthChangeHeal += () => _ui.ModifyHealth(_resourceHandler.CurrentHealth, _resourceHandler.MaxHealth, HealthModifyType.Heal);
}```
To clarify, im basically trying to make this without having these additional events. I could make a function inside the class assigning this but im trying to avoid it.
you need to accept the parameters in the (), but realistically you wanna just make a method for this like
void MethodName(type variableName)
{
}
then subscribe it _resourceHandler.OnHealthChange += MethodName
ahhh great im triyng it out now
thanks
works like a charm thanks!
Is there anyway to load into another scene while simultaneously clearing all "dontdestroyonload"ed objects? bassically transitioning into a scene as if you are booting up the game for the first time?
use an event that your DDOL objects subscribe to. or don't make them DDOL
what are some cases where delegates are handy.
When I look up the docs, I can't imagine cases where its useful (i know they are, i just dont find some cases).
also, there is this example in the dotnet doc:
public delegate void Callback(string message);
// Create a method for a delegate.
public static void DelegateMethod(string message)
{
Console.WriteLine(message);
}
// Instantiate the delegate.
Callback handler = DelegateMethod;
// Call the delegate.
handler("Hello World"); // <= what happens here ? does it call "DelegateMethod", or does it "save" its call
I don't know what you mean by "save its call" but invoking the handler variable invokes any delegates assigned to it. In this example that is just DelegateMethod so this would result in printing Hello World to the (non-unity) console because the DelegateMethod accepts the string parameter and just passes that to the Console.WriteLine call
so this almost act like a any method, the difference is you dont need a instance of any class to use it (except the instance handler)
yeah i guess i can do something like this. i thought there would be a simplier way
delegates are basically ways you can pass methods around as variables. this does include instance methods
im currently working on a system that takes users to a ban screen if banned and if they are unbanned while sitting on the screen i want to transition them back to the main menu fresh as if they are just loading in for the first time
Hi! Im trying to get the height of a 2d object so that I can loop through a list. The code in the screenshot if the code I used, but height remains the same even though I have a bigger screen. The consequences? Well, when I am in the unity editor with the game window small, it looks good, but when I zomm in on the game, it messes up. Any fixes?
ah okay i forgot that, thats great
what would be the synthax to add as a method arg a delegate/another method so you can call it inside the method ?
you've got your game view set to free aspect so when you "zoom" it's just changing the resolution/aspect ratio of the view
I used currentItemOffset -= prefabInfo.rect.height; when I loop through the list to instantiate it downwards
it's not any different than any other type as a method parameter
and whats the synthax for that ?
yea, but how can I get the heigh of pixels?
why don't you first learn how to properly anchor and scale your #📲┃ui-ux so that it doesn't change to random sizes
have you never written a method with parameters?
this is the idea
void DoSomething(? somemethod){
// stuff
somemethod();
}
can you pass values in this method ?
you put the type of the delegate you want to use as the type for the parameter
okay
thats an help channel, am I supposed to ask this there?
well you can start by reading the documentation pinned in that channel to learn about how to set up your UI correctly
you can also look into things like Vertical Layout Groups instead of manually finding the height and assigning the position
this is a code channel
Hey guys, tryna reference my interface to execute a function in a scenemanager script but keep finding an error
Here is the trigger function with the definition that is erroring:
private void Start()
{
sceneManager = FindObjectOfType(typeof(IScreenManager)) as IScreenManager;
if(sceneManager == null)
{
Debug.Log("No Scene Manager for Level Trigger");
}```
Here is the interface alongside the scene manager (which is in the scene):
```public interface IScreenManager
{
void FadeOut();
}```
```public class SceneOneManager : MonoBehaviour, IScreenManager
{
public static SceneOneManager instance;
//etc```
I keep finding this error upon play however:
Fix the errors from top to bottom.
The first error states that you can only use find with objects that derive from unity object.
hello I need help please I made a script in python to develop a 2d game I made the script to make a character move up down right left but when I want to try on unity it doesn't work can't anyone tell me how to do it
unity uses c# not python
Oups sorry i would to say c#
Not python
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{ public float moveSpeed;
private bool isMoving;
private Vector2 input;
private void Uptade().
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("vertical");
if (input != Vector2.zero)
{
var targetPos = transform.positition;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while (targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
IsMoving = false;
}
Your coroutine isn't inside your player class.
you need to start by getting your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
yeah no stupid rushing and not reading errors once again, was trying to speed run modularity without an extra script in between
ty for the point out
I'm a beginner and I don't really know what should I change?
they are saying that your coroutine is actually outside of your entire public class player
move it into the class by shifting it up past the bottom }
You also have public variables inside a method which is not correct and you misspelled Update
Seems like a mess, start with configuring your code editor, see the bot message
I didn't even notice that they were all inside the Start method.
It should have been caught by your configured IDE #archived-code-general message
Here is my solution. Get all root GameObjects in scene Use GetComponentsInChildren on each (it works with Interfaces) Return list of interfaces found Here’s the code: Gist: FindInterfaces.cs · GitHub using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; namespace Glitchers { pub...
is there someone delete his question or i am lag
I did what you told me and it doesn't change anything I'm sorry I'm having a hard time
follow the guide
hello
i tried adding a delegate in my code, but i am running into an issue.
Here is the code:
private delegate IEnumerator UnloadAsyncEndedDelegate(string sceneToLoadAfterwards);
StartCoroutine(UnloadAsyncScene(0, new UnloadAsyncEndedDelegate(LoadAsyncScene(choosenScene))));
private IEnumerator UnloadAsyncScene(int sceneIndex, UnloadAsyncEndedDelegate endCallback)
{
// some code
endCallback(); // how do i get the string argument ?
}
private IEnumerator LoadAsyncScene(string choosenScene) { }
for now the two issues are :
- how do i pass the string into the callback when calling it ?
- in the
StartCoroutineline i got a "need a mthode name" error
okay i found the issues, i was totally not using it in the correct way :)
Is this the place for help with code, or is there a designated area?
thanks, i appreciate it
hello guys I desperately need some help with unity, I've been cracking my head about this the whole morning. If anyone with some expereince would like to take a look at my reddit post that would be great
I don't think it is that hard to fix, maybe I'm just overlooking the soluti9on
do you have a second instance of the script on some other object in your scene by mistake?
I will have a look, thanks
that was it! holy shit I'm so stupid. Can't thank you enough man
we've all been there at one time or another 😄
One trick for that, if a script on a gameobject throws an error, single click the error in console and the gameobject will be highlighted
you can also make your Debug.Log do that by doing Debug.Log("text", gameObject)
good to know, thanks!
Scene scene = SceneManager.GetSceneByName(choosenScene);
GameObject[] sceneGameObjects = scene.GetRootGameObjects();
sceneGameObjects[0].SetActive(false);
Bounds bounds = _bigBackgroundScenes[sceneName];
Vector3 offset = new Vector3(
(_loadedBigBackgroundScenes_Names.Count < 1 ? _player.transform.position.x : _loadedBigBackgroundScenes_Bounds[^1].center.x + _loadedBigBackgroundScenes_Bounds[^1].extents.x),
0,
0);
sceneGameObjects[1].transform.position = offset;
bounds.center = offset;
Debug.Log("position of " + sceneGameObjects[1].name + " in scene " + choosenScene + " set to " + offset.ToString());
here i am loading a scene, getting the root gameobject (sceneGameObjects[1]), and setting its posittion.
when I read the outputed debug logs, all the positions are correct. But when i go check in the transform component, sometimes the position isnt correct
why is this happening ?
#1 dont load objects by iteration id, either give them a singleton script or tag them and find them by tag, what you are doing can break at any given time
are you executing your stuff right after loading? are they on a totally different position than they should be or a bit off, maybe 0,0,0? did you log the position they should be on and is that different to their actual position?
there is no iteration ?
sceneGameObjects[0]
well its getting the first item in an array, i dont see the problem
move any object, have any plugins auto create an object and it breaks
just tag the object you want to deactivate with something and look for the tag instead
yes i know, but this is how I structured my scne template so i wont have any issues with that
i cant work with tags because multiple will exists eventually at the same time
GetRootGameObjects isn't guaranteed to always return the objects in the same order
just make a manager script or whatever, have a list on there and drag all scene objects into it, list is always ordered and you dont have to deal with hierarchy ordering differently
well neither of the 2 root GO have the position changed to the correct one
they just have there default position
i'll just remove the other root, so there is only one
there are 3 scene loading in async in additive
are you waiting for the async load to finish before you change the positions?
2 of the transform are at 0,0,0
one of them should be at 210
well I cant get the root objects without the scene finished loading
but yes i am
ok, when do you execute the position changes?
this code is just above the snippet i posted above
when i go check in the transform component, sometimes the position isnt correct
Are you referring to checking via inspector?
here
have you debug.logged the position that your script is calculating for the objects?
Inspector would show the local values
well its offset, i am using it in the debug log
You'd want to log the local values to print the same value as what's in the inspector
Or set the localPosition to have the inspector show your expected value
ran other test, sometimes they are all at 0 0 0
local or world, why is it working/not working "randomly" ?
if this was the issue, i think it would always fail or work
What failed to work?
I'm still catching up with chat
Don't see anything about failing to work.. just comments about not all objects being available yet or position being incorrect etc
the transforms arent to what i set them to
The inspector values are the local values
well, why does these values are correct ? and sometimes not ?
log the local values and see if they match what's in the inspector
Debug.Log("position of " + sceneGameObjects[1].name + " in scene " + choosenScene + " set to " + offset.ToString() + " and should have a local position of: " + sceneGameObjects[1].transform.localPosition);```
the local values are the exact same
the part that make me wonder whats the issue is that the bug doesnt happen all the time
Is there a way to make OnValidate not trigger for all of my scripts the moment I enter play mode?
I'm having an issue calling a serverRPC when running as 'host' i think it might be a timing issue, not sure?
For background, i have a method on a base class derived from rule tile. RuleTile’s custom editor is wacky af. I want to call this method when I’m done editting my ruletile. I cannot use [ContextMenu()] or [NaughtyAttributes.Button(…)] to call this method. I think that has to do with it being in a base class
'RegisterPlayerServerrpc only has a debug.log line
Check out the ISerialization interfaces instead of using OnValidate
works when i run as server, and connect a client OK, but when running as host can't run the RPC
so it'll only update when you serialize values
Oh shit. that is smart
i did not know I can do that. good call
I'm just guessing here but try it
what does Deserializing mean?
like a serialized field in the thing that is now being removed? or removing a whole object? or loading it from the asset? maybe kdk
anyway, I think OnBeforeSerialize is probably really useful for me. Ty
I will probably replace all of my OnValidate with it, because that is what I really wanted
I use it for nested classes a lot because it's a pain to use OnValidate otherwise
Separate question: Let’s say I want to set up like a server, where game just sends files to and from server. Server has validation logic to make sure it isn’t sent invalid files/queries, can query its database, and send them out.
Is this easy to do in unity?
The idea is basically user-made levels
I don’t need full details on how to do it. Just asking if it is easy to do with unity.
With here, I can't call the RPC because it is despawned, where can I put the call to the RPC?
easy enough, you could setup a database with your own custom file format / upload format and use a C# package for downloading files from the server, if there is not an official way
ty
I’m not sure what an RPC is tho
Remote Procedure Call
Could someone please try to help me with this issue, still haven't found a fix
Those screens illustrate well the problem
does it have a rigidbody?
also, I would debug.Log the transform.position as well.
You want to separate improperly assigned from changed later
I tried, offset and transform.position are always equal
Idk if the position is "changed" afterwards, but nothing else touches transforms except this code
And the werider part is that this issue is random
Place a debug break after the lines of code
and verify in the inspector that it hasn't changed
Im dumb
I found the issue
I am loading scenes, but the same scene can be loaded multiple times
So the get scene sometimes doesnt get the "correct" one
Because same name
Is there a unique identifier i can save to get a specific scene ?
From memory there is only getScene using path and using name
And build index
But those will all have an issue when having multiple identical scene loaded ?
I made a public static class with public const int with indices for specific build indices for each scene
SceneBuildIndices
this is super easy; and way faster than any “smart” solution tbh. At least in my case, where I have 4 scenes in the whole project
i dont understand how this would work with loading scene and knowing "this new one is <this scene>"
ig SceneManager.GetSceneAt it the solution for me
you can load scenes by build index
its retreiving the scene the problem
why is that the problem
because i load multiple time the same scene
and?
its like having a dict wit hsame keys, how does unity know which one to get ?
loaded scene:
- scene1
- scene1
- scene2
GetSceneByName("scene1") > random or first item
its additive
that isn’t two scenes. that is two whole sets of objects
i have good reasons
Why is it a scene and not a prefab
but i found the solution sor there is no problem now
thats a good point
that’s why this doesn’t make sense
i wonder why i didnt do prefabs
just fix it now
probably because it was going to get filled withy tons of objects far away
then just break or disable the prefab
well, you cant load with async a prefab ?
if i remeber i think thats why i used scene
can’t you just instantiate it with an async method?
the point of a scene is to destroy everything, and bring in everything from a new scene
having multiple scenes at once doesn’t make sense to me
idk if there is one for instantiate
actually gameobjects cannot be instantiated async
idk, but the way you are doing this is strange, my man
ig im strange then :)
ty for trying to help out
How to deal with logging errors from scriptable objects OnEnable() when running automated tests?
So I currently have a split screen with two cameras, and am trying to have one screen "swipe away" the other one, so it now takes over the whole screen.
click on the error to view the rest of the message
if it's UnityEditor stuff, it's probably not your fault; an editor restart usually clears that up
it did o>
I'm using DoTween, so I have things like this
DOTween.To(() => brainCam.rect, (x) => { brainCam.rect = x; }, new Rect(0, 0, 0.5f, 1), transitionSpeed);
DOTween.To(() => diagramCam.rect, (x) => { diagramCam.rect = x;}, new Rect(0.5f, 0, 0.5f, 1), transitionSpeed);
///Other code
DOTween.To(() => brainCam.rect, (x) => { brainCam.rect = x;}, new Rect(-0.5f, 0, 0.5f, 1), transitionSpeed);
DOTween.To(() => diagramCam.rect, (x) => { diagramCam.rect = x; }, new Rect(0, 0, 1, 1), transitionSpeed);
brainCam/diagramCam are Cameras, and I'm manipulating their rects to create this swipe effect
the problem is that when one camera no longer takes up any part of the screen, I get an error and a strange flicker
sometimes...
RenderTexture.Create failed: width & height must be larger than 0
Any idea why I'm getting this?
Neither camera height/width ever hit 0.
Though I guess the size of their contribution to the screen does hit 0?
public void OnInteract(InputAction.CallbackContext context)
{
if (context.performed)
{
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
RaycastHit hit;
IInteractable interactableObject;
Debug.Log("Interaction Action Performed");
if (Physics.Raycast(ray, out hit, 20))
{
Debug.Log($"Raycast cast and hit {hit.collider.name } ");
if (hit.collider.gameObject.TryGetComponent<IInteractable>(out interactableObject))
{
Debug.Log($"Object is interactable.");
}
else
{
Debug.Log("Nice try loser, it isn't working.");
}
}
}
}
My script keeps calling me a loser and I have been looking at code for so long I am sure I am making a really simple mistake. Anyone see my mistake?
this is the code for the object that I am hitting
super simple. Not sure where I've gone wrong.
That is not the code being hit, that is an abstract class
You are getting the component from the collider, maybe it is in its parent?
What object does the log say you're hitting?
What components are on that object?
Hey guys! got a camera clamping issue
if the player rotates the camera any direction it works completely fine
as soon as it rotates up or 'x' too much, it teleports and jitters back
every other direction is fine
am i missing something obvious?
{
rotationInput = Mouse.current.delta.ReadValue() * sensitivity;
float targetRotationX = Mathf.Clamp(transform.localEulerAngles.x - rotationInput.y, initialRotation.x - maxRotation, initialRotation.x + maxRotation);
float targetRotationY = Mathf.Clamp(transform.localEulerAngles.y + rotationInput.x, initialRotation.y - maxRotation, initialRotation.y + maxRotation);
float smoothedRotationX = Mathf.LerpAngle(transform.localEulerAngles.x, targetRotationX, Time.deltaTime * smoothing);
float smoothedRotationY = Mathf.LerpAngle(transform.localEulerAngles.y, targetRotationY, Time.deltaTime * smoothing);
transform.localEulerAngles = new Vector3(smoothedRotationX, smoothedRotationY, 0f);
}```
Do not read back the eulerAngles from a transform.
it's generally much more stable to just keep track of the angles you want and set them
rather than reading euler angles, modifying them, and putting them back
Euler angles can wind up suddenly changing (e.g. from 270 to -90)
This will cause your view to jump when you clamp this new value.
How about some quaternions instead
How can I make a deferred camera as CHEAP as possible if I only want motion vectors and depth(as I am overwriting the actual image)
sounds like some researching, but at most cull the layers you don't care to render as you do
there's more you can probably disable via rendering asset so create a profile specifically for it
beyond what's on the camera component
hey anyone knows why this line of code:
cam.fieldOfView = Mathf.Lerp(cam.fieldOfView,fov,Time.deltaTime*10);
works normally but produces this error:
Assertion failed on expression: 'SUCCEEDED(hr)'
Is there a stack trace?
no
I'm guessing you're trying to lerp the FOV to 0 or a negative value at some point
Alternatively, it has nothing to do with this code at all
im afriad so
i would verify that the code you shared has anything to do with this
remove it and test how the game behaves. replace it with something that just assigns fov to cam.fieldOfView, too
also log the resulting value before assigning it into cam.fieldOfView
see if you're producing a weird result, like 0 or a negative value
don't just log cam.fieldOfView afterwards, since it's probably a property, not just a field
meaning that assigning to it actually calls a method
i did that
the error doesnt appear
there arent any zero or negative values
When NavMeshAgent.Warp fails it logs and error... how can I avoid that? My workmates don't stop complaining about them haha. The method already returns a boolean to determine if it was success or not, so the log is quite redundant.
SamplePosition before warping
Which maxDistance parameter uses Warp inside?
what?
NavMesh.SamplePosition accepts a float maxDistance, which I guess it's the error margin allowed for sampling. Which values does Warp uses under the hood?
Warp does not have the concept of maxDistance, it is your responsibility to ensure that the agent ends up on the NavMesh
light.falloffIntensity = rootLight.falloffIntensity;
light.shapeLightFalloffSize = rootLight.shapeLightFalloffSize;
light.lightType = rootLight.lightType;
light.shadowsEnabled = rootLight.shadowsEnabled;
light.color = rootLight.color;
is there any quick way to copy all fields of one Light2D to another?
structs usually
lights are classes though
I'm not familiar with Light2D but if you want to copy the this component from a GameObject to another, can't you copy component -> paste component values ? Or maybe that's not what you're trying to do
if all the fields are exposed you can just prefab them probably, otherwise you probably want a script that access those values
so a prefab for each component setup, or a single prefab with different data assets
anyone have any tips for hooking a particle system renderer up to a UI slider? this is the code I have for it cunrrently, and it gets the references but doesn't actually change anything in the material.
To be precise, lights2d inherit mono behaviour which makes it a components
I'm doing it in script
for context, I'm generating 2d freeform lights for a tilemap
I have a 2dLight on the tilemap itself that I'm using as a reference for the values
Hello. I'm on 2019.4.40f1. Our project has issues with instantiated prefabs returning null for GetComponent after Instantiate, but only after the game has been running for a long time. The prefab comes from asset bundles. Something like
if(BundleManager.TryGetInsance("MyPrefab", out GameObject instance))
{
var component = instance.GetComponent<MyComponent>();
if(component == null) Debug.LogError("Null component");
}
The message starts triggering 100% of the time after long gameplay sessions. The original prefab template is not known to be modified otherwise.
I'm wondering if it's some sort of asset garbage collection issue, or a known engine bug when it comes to prefab instance components
I can provide more context if needed, it's an open source project
pSR.material.SetFloat...
What's the exact error?
What's shown in the console window?
The error log from the snippet, which comes from GetComponent returning null
I'm assuming instance was null rather than the component missing
instance was null
You can try making an extension which deepcopies your class instance, and set the new instance directly instead of the new fields
How so? I would have a null reference error calling GetComponent, no?
Show us the error log from the console
this was a good idea, but still did not change the value for me. This would work during runtime correct?
Here's the real code and my logs
tornado mat would only be a clone and not the actual material
Note the line numbers. This only occurs after 30k lines of logs, and then it occurs all the time
So it wasn't an NRE.
The component was removed from the object.
this is what I changed it to, wouldn't this get the material?
Yes I've mentioned it was not a null reference exception, it's the component that's null and we check for that
I don't think any code could possibly remove it from the prefab, but worth considering I suppose
Thinking about it, isn't if(component) special in Unity where it does extra checks in addition to checking for null? I can't remember if that's MonoBehaviour or GameObject
You'd only get null if the component was removed or if the component type you're searching for doesn't exist on the object.
I'm assuming your component isn't called MyComponent
It works multiple times before starting to fail all the time, so I'm confident I have the right one. There's no code in the repo that access the prefab other than to Instantiate it, hence my conviction that the prefab is not modified
The error occurred, meaning the above is likely the case
when i have a list of a list like List<List<int>> roomMatrix = new List<List<int>> { new List<int> {0, 0, 0}, new List<int> {0, 0, 0}, new List<int> {0, 0, 0} };
and you refrence it like myListOfList[][], is the first square brackets horizontal or vertical
the first is vertical, the second is horizontal, based on your code
cheers
anyone able to follow up on this? I still cannot get the values to sync
@upper wigeon are you sure that Dissolve is the actual name of the field ?
Sometimes when using for instance shader graphs you need to use the reference name, not the name itself
haha no prob bro
of course, why not?
Destroy is not a magic function. All it does is put the object in a list to be destroyed at the end of the frame.
And to "destroy" an object simply means that the C++ half of the engine discards and cleans up the memory associated with the C++ half of the object
it doesn't affect the C# half of the object at all really, other than the scene throwing away its reference to it.