#archived-code-general
1 messages · Page 359 of 1
oh
alright chat, ive been looking into Unity event systems but after seeing what it does im not sure if its fits my situation
so, i have a player entity. that entity can perform stuff. so what i (would) want is a system that has Events (like onHurt, OnRun, OnAttackHit, Etc)
how would i go about doing this
my initial thought was having a central Event Monobehaviour with all the On* events. then in other classes (like movementcontroller, healthcomp, weapon classes) whenever the [moveclass] detects when you press shift, it would also signal OnRun in this case
then i can make components that subscribe to these events, which in turn execute specialized code
so, the ultimate question, is this the right way to do it?
are my thought going in the right direction or not
No big secret. Either C# events or UnityEvent
UnityEvent if you want to set up the subscription in the inspector
Otherwise, regular C# events will do
I don't see a reason for a "central" event behavior
The movement system would fire the movement events, and so on
Keep it simple
so instead of putting these Events in a central class i put the movement related events in the movement class
got it
how do I make my character jump using the Input Actions?
If you want to have several entities, you better not make the events static.
I use UnityEvents for everything. But the whole point of events is to avoid central manager classes, as Praetor said.
Unity events are pretty bad for maintenance. Can't refactor easily, can't find references to events in code. It's basically a crude tool for giving gamedesigners on your team a crappy form of visual programming with no safeguards.
This is typically called an event or message bus/queue/broker. Maybe read up on that pattern and see what the pro/cons are before investing into any kind of heavily event based system. Typically an event based system (for game logic) is potentially very difficult to debug.
What theme are you using ?
why sheep don't spawn
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.
presumably because gameManager.SelectedItemsList is empty
or the script is just not running
Hi all, I was wondering if anyone knew if their was a way to speed up gizmo rendering. I'm writing some really quick prototyping code that just displays the colour of cells in an area (currently 50, 50) this is fine but I want to expand this further and have a larger area displayed. At the moment though it is already noticably laggy in the inspector is their a more optimal way of doing this (that isn't printing to a texture or something simular as this is meant to be a quick prototype that I am repeatidly changing)
I'm currently using Grizmos.DrawMesh and passing in a Quad, are handles more optimal for these things?
Are you drawing a mesh for each cell?
does anyone know why it does this and how to fix it?
ends up breaking the whole project then having to restart from scratch
Yeah
The colour of the mesh is determined by certain states of the grid, so its just meant to visualise different data
So the way I'm currently doing this is just using a switch statement to set colour based on different states and then rendering at a given coord the mesh
That will be pretty slow yeah. DrawCube may be faster to start with
anyone here used mixamo ?
Right now I get a simular kind of render time from both, my guess is DrawCube is more optimal, but Drawmesh only has to draw 2 triangles rather then the 12 for the cube. I guess with this being said, is their away to force Gizmos not to render stuff behind them? (z culling but only on gizmos)
this is a coding channel
Go to #🏃┃animation
And !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Second question, I was wondering if Unity had a noise function that would work for "infinite" ranges. From what I have seen Mathf.PerlinNoise only works for noise between 0 -> 10. Looking at the Mathematics functions it is very unclear on if their are ranges or not given how its barely documented https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/api/Unity.Mathematics.noise.html
Is their any better documentations with examples of the outputs for these noises and their ranges / limitations?
WTF is the range of a noise function ?
that depends on your noise function
Are you talking about the period of the noise ?
Usually Classical Noise will be -1->1 as well as simplex noise
Mathf.PerlinNoise is "infinite" (the entire float range)
Some noise function just flat out stop working if you go beyond their range, the Mathf.PerlinNoise doesn't have a repeating period it caps out a 10 seemingly and only generates 0.47.
I can confirm this really is not the case, I'm testing it with values in the 1000's and every value I get is ~0.47
Perlin noise generates the same value for all integer inputs. That's probably throwing you off.
Hmm, let me check. I am 90% sure that the values I am passing it should be going up in a 0.05f step but I may have messed something up
Thanks, thats good to know though xD
Ahh, yeah your right. My bad. Sorry Dx
I was sampling the position but not adding the 0.05 offset so it was taking the integer position each time.
Looking good now! Thank you
for some reason my y fotation goes to -360 or smth like that https://www.toptal.com/developers/hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Please don't crosspost
This is the third channel you've asked in? And you're being answered already
srry
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello everyone. Idk if this is the right channel to ask, but i have a question regarding my current setup and ways i might be able to improve the current workings or completely revise how it works.
Right now i have a building system which consists of cubes. Cubes can be attached to eachother which makes them act as one object (by being children of the same rb parent) as well as detach from eachother and seperate the attached cubes if necessary.
Currently i handle detachment by storing what is attached on each cubes face and using a bfs algorithm to traverse the cube structure and check what is attached to what after removing a certain cube, though when doing this it might cause a significant lag spike depending on how large the structure is. Any way i can improve on this or another way to handle this?
Placement manager (calls attach and detach methods): https://gdl.space/lopafotajo.cs
BlockManager (handles the attachment and detachment): https://gdl.space/baqezopeya.cs
Is there a way to make this work from the base class?
go.GetComponent(GetTargetType())
_> Code ASMR just popped up (all of the semicolons lined up perfectly)
That is pretty nice. My compulsion would make me put the two TMP_Texts and two GameObjects together
Is there a reason you need the separate GameObject references?
Also the other components are probably on that gameobject
How to make a 3 sec hold button?
with a radiant progress bar
Quick hiccup I'm dealing with here: I have a series of health bars and other informational gameobjects tagged as "DEBUG" for a script to let me activate and deactivate them. The script is completely detached from anything that is tagged, and I double checked that the bools in the script are acting as needed. The issue is that for some reason GameObject.SetActive(false); works just fine, but GameObject.SetActive(true); does not.
Is the code running? Use debug.log to find out
yes and the bools are switching just fine
Deactivating them works just fine, but when I press the button again, they don't reactivate. Once again, the script isn't attached to anything that is tagged.
Late reply but this is what I'm gonna go with.
Found an implementation here (https://blog.theknightsofunity.com/pathfinding-on-a-hexagonal-grid-a-algorithm/) that's compatible with the axial coordinates from redblob
wow this is a pretty great find!
Wait does GameObject.FindGameObjectsWithTag not return inactive objects?
have you read the documentation
not yet, I only just now considered that
that should be your first step before asking usually
that one little word "active" hiding in there 🙂
s'ok, honest, I think it's kind of a gotcha about unity
FindObjectsOfType can return inactive objects if you specify so
is there a way to prevent a setactive?
I want to intercept a setactive call to keep the object active for an animation before setting it to inactive
the way i have it currently works but its stupid
Hi Unity friends.
I'm meeting a conundrum that I feel like there should be an easy solution to but can't figure out the right call.
I have a game with AI that follows/ attacks the player. There are some gameplay elements that dynamically cause zones to get temporarily covered in fire. I want AI to avoid walking in theses zones if possible. The player has access to a kick and can kick (physics) the AI into the fire zones.
My first solution was to use nav mesh obstacles. That way the AI correctly avoided the fire zones. However, since nav mesh obstacles CARVE the navmesh, enemies kicked into it instantly teleport back to the nav mesh.
I've heard that unreal has stuff like a "weight" logic where you can add "weight" to parts of the navmesh so that NPCs TRY to avoid these zones but still know how to navigate if they're in it. Anyone know if there is a similar solution (or a different one) to this issue?
Try using area costs
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
I know about those but, dynamically?
Can't navmesh volumes (to setup areas) only be used when baking?
outdated manual oops
I have no clue, it would be a better question for #🤖┃ai-navigation
Alright, thank you!
Hi! Fellow Unity Users, How are you all doing? this is the first time i use Unity 3D and i am still learning so i am currently stuck without knowing how to code.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
There is also visual scripting
visual scripting
..yep?
yes
i'd recommend just doing this though
And is visual scripting hard?
its maybe easier to understand at first than normal coding
its about the same difficulty overall though since you're doing the same things
also most tutorials will not use visual scripting
But it's easy to learn it then.
I would say the difficulty ramps up substantially given the general lack of documentation and poor support
exactly ^
The question is if it’s even worth learning
its easy to start but learning anything in depth will be difficult
Which practically, not really.
i dont know anyone who uses visual scripting in unity other for things like dialogue or behavior trees
You need to wrap your heads around the same concepts, but in a format basically no one uses
not for writing all code
Without the advantage of years of free educational resources focusing on C#
i actually might try to use visual scripting for my UI stuff
easier than making a million little code scripts for each button
I usually just make one class implementing the various Ipointers and then pass in delegates for what to do on each button, enter, exit etc
It's either visual scripting or C# one of them has to be excluded.
its just tedious writing UI code in general
idk nobody else ever complains about it but working with unity UI is super slow
im guessing thats what UI toolkit is for, havent tried it yet
def do C#
C# is an actual marketable skill that is applicable outside of Unity and also provides the greatest level of flexibility
visual graphs look like shite
Visual scripting is a gimmick to get people to switch over from RPGMaker and Gamemaker
Unreal blueprints are a lot more tightly integrated
and faster
still looks like shit
so does C++ code imo
Header files 
yes i rather look at the graph in that case then deal with C++
The few times I had to deal with it I just used UnrealCLR
But unitys approach to a lot of, well stuff, is just much more open ended and imo more intuitive
man i could already be done writing the script by now
i guess its not even good for that (edit: i think this may just be the first time you use it?)
Why can't I add a mesh collider on a parent (and then link the child gameobject with the mesh)
you can, did you drag the mesh on child inside?
the mesh itself not the component
yeah, won't let me .. It's NBD, just for organizational reasons, but it appears as if the mesh collider has to be on the same object as the mesh renderer
ooooooooh, that's what i did
click the mesh filter on the child, it leads to you to the mesh then use that instead
How to create a single game just like the Blood 2 The Chosen game series?
Was it 2D or 3D?
The original game.
I just googled "blood 2 2d or 3d" and it said 2d
Ah yeah, i just read the blurb
The original Blood won numerous fans, despite the fact that it was a 2D shooter released nearly a year after Quake made 3D environments standard.
Please don't send a google link that takes up my entire screen
Glad you found something. No need to actually post it here...
Was just trying to show that you can actually access Google yourself to look. Not really a question for here
also this is a code channel @modest sun
I just found a better way to post the link.
No need. You are the one that wanted to know.
Any tips for debugging raycasts & cinemachine? I have a bit of code that seems like it ought to work.. but doesn't:
private HexPoint _lastMouseOver = HexPoint.None;
// private int terrainLayer = LayerMask.NameToLayer("Terrain");
private void CheckForMouseOver()
{
v($"Mouseposition is {Input.mousePosition}");
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
HexPoint targetHp = HexPoint.None;
if (Physics.Raycast(ray, out hit, 100f, terrainLayer))
{
Transform targetTransform = hit.transform;
TerrainHex target = targetTransform.GetComponent<TerrainHex>();
// snip validation shit here
targetHp = target.Location;
}
if (targetHp != _lastMouseOver)
{
v($"Location of mouse changed to {targetHp}.");
_lastMouseOver = targetHp;
}
}
Where to post it?
Nowhere. Why post it? You were the one with the question. You found the answer. Done
Good work on getting the correct answer
Do you know how to program a original game similar to the game series?
That is a MASSIVE topic
I mean, sure, I could probably figure it out. But could I explain it to you here? Not really
It's some simple game... they didn't have Unity at that time.
Simple games still take a LOT of work. If you have specific questions we can help. But "how to make this game" is waaaaaaaaay beyond what belongs here
Have you made games before? If so, you should understand why
I started doing a shooting game on Unreal Engine 5, but i didn't have the balls to continue doing that.
Go through !learn and do all the projects in the Junior programmer pathway. Then find some other projects on youtube and do those. Then START thinking about your project
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Visualize physics queries and step through the logic. Cinemachine simply controls the camera, so anything camera related here should be the same as long as the physics query ends up looking right.
btw Physics Debugger in 2022 & 6 allows you to see Casts and Overlaps
Yeah.. Just curious how? I'm a bit newer to 3d work. I am tinkering with Debug.DrawRay() but I'm not seeming to see anything.. Spitting out numbers to the console seems like.. it should be working, but it's a bit hard to visualize
yeah you dont even need those anymore
pullup the Physics Debugger under Windw => Analysis

Hm. OK, I must be doing something wrong.. Disabled everything and nothing disappeared. 😛
https://unity.huh.how/debugging/debugger for the stepping through code. Allows you to step through each line and inspect every value.
make sure you have gizmos enabled in scene view
That's NP - I'm just having a bit of trouble understanding why the raycast is failing.. it does look right
Yeah, I just turned those on and saw a flash of a red line - debug.drawray - but then it went offscreen in my cinemachine pan..
I'll try the query, sec
Ok, one problem is that I was using Camera.main and that doesn't give me the "blended" camera for cinemachine while easing between two vcams, but I don't know the solution for that
The other is that I must not have the right components for Physics.Raycast to return a result on my component. What components do I need? I only have a MeshCollider at the moment (or maybe I'm not wanting to use Physics.Raycast?)
Ah, yeah, I need a RB on it.
You only need a collider
not sure exactly what you are saying here but there is no "blended" camera, it's just interpolating the main camera's position / rotation from one vcam to another, it's not creating some new camera with its own position / rotation just for the blend
When I do Camera.main during a 5 second ease in/out - Camera.Main.transform.position seems to only give me the start vcam
Do you know which line its specifically wrong at? Like is it not detecting the object at all
So here's the level - I'm currently doing "DrawRay" from Camera.main to the raycast from Camera.main to mouseposition.. If you look, the red line gets shorter and short until it's a point at the conclusion of the blend
I gotta make a quick call but I'll brb
also I am not sure what the "terrainLayer" currently is since it's not included in the code snippet, but if you are specifying the layer with NameToLayer it will not be a proper layermask. You have to use LayerMask.GetMask("Terrain")
also, you should look at this scene from the scene view, not the game view, otherwise the line will always look weird since its coming from the exact center of the camera
Yeah, doing that is tricky though because of the mouse position (it goes off screen when I go to pause it, so it points in a wild direction)
i just put the game and scene view side by side
hmm I have my unity layout set up so I can have the scene view and the game view open at the same time so that there is no reason to pause
oh derp, of course, i'll do that
hm.. I changed the layer mask but maybe I'm doing this wrong.. I'll have to google
private int terrainLayer;
private void Awake()
{
terrainLayer = LayerMask.GetMask("Terrain");
}
private void CheckForMouseOver()
{
// ...
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
HexPoint targetHp = HexPoint.None;
if (Physics.Raycast(ray, out hit, 100f, terrainLayer)) { ... }
}
I just need the mask of the layer I'm looking for, I assume
like a bitmask
I would change the type to LayerMask, although I am actually not sure if it matters?
(talking about the terrainLayer variable)
I could do that - I just memoized it because it seemed bad to do in every frame
maybe that's a problem, too, losing somethign important in the implicit cast
oh, no, GetMask returns an int
I dont mean cast it every frame I mean just change the type.. doesnt the overload take a LayerMask? or is it doing a cast in the function call
ah okay then
guess it makes sense
do your colliders actually exist and function properly? it looks like a custom mesh
what type of collider are you using?
mesh collider
so the raycast is definitely.. working as I want it to, I'm just not getting the target in Physics.Raycast
I would just log what I was hitting then..
Oh, it's not hitting
That's what I mean - nothing's getting hit at all.. Physics.Raycast returns no items
your message confused me
but okay yes can you just spawn a cube and give it a rigidbody, and have it properly collide?
sure, lemme try
(and im sure you have quadruple-checked your layers are correct on the cell objects)
I'm pretty sure.. I have this in the init for the cells:
public void Initialize(HexPoint p)
{
int terrainLayer = LayerMask.NameToLayer("Terrain");
if (gameObject.layer != terrainLayer)
{
w($"Hex {p} does not contain the Terrain layer and will not function properly with raycasts. This is a bug.");
}
(and it spammed up the console - as I expected - until I set the layer properly on all the prefabs)
as a sanity check, can you also show the code with the draw ray lines.
when i have raycast troubles ill normally just try it on a cube first
private void CheckForMouseOver()
{
v($"Mouseposition is {Input.mousePosition}");
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
HexPoint targetHp = HexPoint.None;
if (Physics.Raycast(ray, out hit, 100f, terrainLayer))
{
d("Ding!");
Transform targetTransform = hit.transform;
TerrainHex target = targetTransform.GetComponent<TerrainHex>();
if (target == null)
{
w($"Raycast hit something ({targetTransform.gameObject.name}) that wasn't a TerrainHex. This is a bug.");
return;
}
targetHp = target.Location;
}
if (targetHp != _lastMouseOver)
{
v($"Location of mouse changed to {targetHp}.");
_lastMouseOver = targetHp;
}
v($"Cam position is {Camera.main.transform.position}, ray direction is {ray.direction}");
Debug.DrawRay(Camera.main.transform.position, ray.direction * 100000f, Color.red);
}
here's everything, unedited
_lastMouseOver is just memoizing the last hit hex - my plan is to show a "highlight" hex as you mouse over, but I didn't want to be doing it every frame for every hex, so I'll just emit an event when it changes
I am confused by this, what is the drawray meant to tell you then? are you determining its not hitting using of your target == null check?
"ding" never happens, ever
ah
okay so then yes, I would make sure the mesh collider is actually generating properly
ok so raycasts work on the cube.. so something must be broken on my mesh collider
if (Physics.Raycast(ray, out hit, 100f, terrainLayer))
{
Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.green);
}
else
{
Debug.DrawRay(ray.origin, ray.direction * 100f, Color.green);
}
doesnt fix the issue but i would use draw ray like this
do those layers (include) need to be set on the ~~render ~~ meshcollider?
render collider?
no, they dont
could it be somethign with the normals on the mesh itself?
I didn't generate the mesh
hm does it need to be convex?
also - "convex" isn't checked, does it need to be?
I dont think it would, as you can definitely raycast against objects in your level like a house or something, which have a mesh collider (I mean as a general use case of raycasting)
It is a convex mesh, I suppose I'll enable it? (not sure why it needs to be, seems like it's an optimization for properly normalized meshes?)
just for funzies, I would enable "queries hit backfaces" in the physics settings of your project
and see what happens
but its possible it failed to generate the collider entirely
because of some weird non-manifold geometry issue
I dont believe so either, none of my models have it checked and the mesh collider works
but you could try the convex option on the mesh collider, although its less of a fix and more of a bandaid
(assuming it works)
ah! something worked
either me enabling convex or me enabling backfaces
lemme turn one/other off
maybe the normals of the faces were pointing in weird directions, if enabling backface worked
Yeah, it works now that I've enabled convex on the mesh collider
weird that it didn't before!
I'm imagining that this mesh has f'd up normals? maybe it's even inside out?
I didn't generate this mesh but don't know how to check
i could take a look if you dont mind, though im no blender expert i dabble
it would render weird if it was inside out though, so I am not sure
seems pretty simple / normal to me, however I am not sure how the mesh collider handles scenarios with open faces like this
so maybe it just decided it couldnt do it and didnt generate a collider
although I wouldn't exactly expect that to be honest
oh, it doesn't have a bottom?
yeah
yea this looks a bit off
maybe the collider needs 2 hits to be a collision? ie, one on the front face and one on the back face?
I bet that's why setting it to convex worked - it only looks for one collision on an "outside" face
convex does fix this issue though (I mean conceptually, it would fill in that gap) so seems like a good solution for this
yeah exactly
something like that
weird one, well, TIL
could also try filling in the face, if you select the whole edge loop with (alt left click) then press F it should be fine as is. Although not sure if thats truly gonna fix it, thats how you would make it a complete shape
its more ideal to not have an extra render face that you will never see so its fine
convex works
It's no problem to use the convex solution - it's actually probably an inadvertent optimization
But I'll probably long term want a bottom to these hexes.. in case there's any sort of physics stuff with the hexes going flying or whatever
ah yea you'd have to do it in blender
right now, you should see through them if looking from below
Could do it with ProBuilder.
yay.
victory
I just did this for myself for learning but if for some reason you need the other side filled in, try this. I tested it, and the raycast works while it isnt convex
Awesome, thanks!
i also dont know what export settings was used when it was created, i noticed this object isnt centered and was slightly rotated lol
rotated by 0.0009
Wanna do a couple hundred more? 😛 3x3, 6x6, and so on 🙂
"this isn't what I signed up for"
Good to know on the rotation .. I don't think it'd matter? But it might be visible along the edges/corners
In fact...... lemme look closely
it was probably just floating-point error on the import to blender, or the export from blender in the first place
nah they look fine to me, even under scrutiny
yes its a very small decimal so not noticeable
they're just temporary assets anyway.. we're still sorta worldbuilding
oh sorry it wasnt 0.0009, it was -0.000009
haha
yeah that's probably fine
(although I am the kind of person who will type 0 into the rect transform values over and over until they settle on 0)
Ah darn, memefree zone. 🙂
Anyway, you know what I'm talkin about. Feels good man.
😛
Hello, is there an asset or package can assist with GameObject vertices/edges/faces selection process? My aim is to manipulate elements position
Hope converting a mesh to triangles meshes that each one contain a unique collider is not an option xD
Not sure exactly what you're asking but.. ProBuilder maybe?
I've been trying to use that ElementSelecion but it didn't go well (bugged for me)
Like imagine having a game object on a scene and you aim to modify its vertices or faces with translation operator
I want to let the user to manually select vertices / faces or edges if possible and apply necessary changes
Yes pretty sure the runtime API of ProBuilder will let you do this.
Hello! I am VERY new to unity and programming in general but I was wondering if anyone had a fix for this? It is probably something simple i am doing wrong
Basically i want to hold the wand and have it collide with objects, i set the default XR grab interactable on it with "velocity tracking" movement type and it seems very jittery as seen. Do yall know how to fix this and still have it collide with objects? pictures of the settings following
lemme know if this belongs in another channel
Since i dont plan on using alot of grabable objects, a possible solution (more of a workaround) ive been thinking of is to have a solid body that looks like hands follow the hand position instead, making the controller hands themselves invisible. the solid objects would get stuck on the geometry if it follows using velocity and i could switch out the models using area triggers (ex: pick up want here! and when the selector is activated in the designated area the rigid body would swap out for a hand holding a wand instead). The wand wouldn't be throwable though which isnt an issue for me
This solution seems very performance intensive though to constantly have a rigid body track the hands. and its still using the underlyig principle of velocity tracking which doesnt seem to be working out well for me right now
how do you change material data in edit mode on a per object basis? since you can't use .material since it warns about leak when not in play mode. but using sharedMaterial effects all objects
kind've damned it you do, damned if you dont
Anyone have a méthod or Know a méthod to make a sphère based on cubes? Like Minecraft? In coding i mean
find the width or height either one then the sphere is the position and the radius is half the width or height
oh wait you mean to voxelise a sphere?
a flood fill will be the simplest way based on the sphere bounds then remove any cube that is not within the radius distance
Well it's right because you would need to make a new material. So I guess you make a new material asset and save it and assign that.
hm i see. wish they could come up with some kind've virtual material which is instanced in edit mode then discarded 😦
since i only really need it at run time but need to test it in editor
im sure its a simple fix, i just dont know what setting i have wrong XD
do any of you suggest a project? I’m a beginner and I’d like to expand my knowledge on object oriented programming
OOP can be applied to any project, so pick whatever you're interested in.
is anyone here?
PLEASE HELP It has been 2 days. I can't make this work!!
Question
Hello. I am making a hyper-casual game in Unity. I am currently working on the gates that have numbers like “x2” or “+50k” or “-7k”. I assume you already know how these gates work. But the problem is… For some reason, the variables are working as static. If I assign the gate script to one gate. It works perfectly without any problems. But if I make 2 gates & assign the same script to the 2 gates. Both gates do only one modification.
Example: First gate is set to +500. Second gate is set to -600. If I play the game and collide with the first gate. I get +500. But if I collide with the second gate. I still get +500. But… I am supposed to get -600.
Thats the problem. This is my script. Please help me. For the love of god, end this 2 days of suffering!!
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
please help me on this
your explanation is kind of vague, but I'm going to guess both gates are triggered at once and whichever one happens to receive OnTriggerEnter first does its operation and sets the other one to done. If that's not it, provide more info about how they're set up
look at these 2 vids
please help T-T
most people really arent gonna watch long videos to attempt to debug your issue. you should debug to see whats happening. you cant just start the problem with "i assume you know what gates are"
i assume you know what gates are
dude. you can look at the vid for 3 secs and you will understand what the gates mean
🤷♂️ im just telling you the truth, people wont help when the first link i click has a 3 minute video and it seems you made 0 effort to debug
what debugging have you done? what happens if you set a breakpoint in OnTriggerEnter? Why didn't you rename your GameObjects properly? Did you try disabling one of the gates? If you had these two videos already (which ideally would have been screenshots), why did I have to drag that info out of you?
... no. I actually spent 2 days. I posted about this in Unity Forums. No one responded. I posted in reddit. Got alot of answers. But none worked. Tried youtube tutorials, google searches. Nothing worked...
Someone in reddit asked for a vid recording so i thought you guys might ask abt it too
Try adding some actually useful Debug.Logs
Disabling one of the gates works fine. It doesnt cause any problems.
Like where
Like the first line of OnTriggerEnter
Forget this. I found the solution.
The collider wasnt moving with the hand
2 days wasted
In blender, I made a non humanoid armature with an ik bone. When I import it to unity, when I try to move the ik bone towards the player through a script, the rest of the armature doesn't follow along with the ik bone. How do I go about fixing this?
why would the color utlity have an error? it works on my other scripts?
ColorUtility does not actually return a value
through the "out color" part, it sets the variable color to the output
you cannot set a local varialbe to itself when declaring it
but it itself, doesn't return anything
actually it might be returning a bool or something if it succeded or failed, you'd have to check the documentation
tbh, that whole statement makes very little sense
The statement is a ternary expression so it does make sense to use it like that
Though only ColorUtility is underlined, so maybe you have your own class named that, so there's an ambiguity between yours and Unity's?
Sorry but it doesn't, let's break it down
Declare a variable color
Evaluate the method and set the out to the declared variable
If the method was succesful set the variable to itself otherwize set it to black
In my book this makes no sense
It's valid though
I did not say it was not valid
It works, yes it assigns twice but it does the thing as intended
default(Color) might not be black so the ternary acts as a default value assignment
It's a short for
Color col;
if (!ColorUtility.TryParseHtmlString("", out col))
col = Color.black;
Actually it is not, it is short for
Color col;
if (ColorUtility.TryParseHtmlString("", out col))
col = col;
else
col = Color.black;
which you would never write
You know that out acts like ref right? So your snippet is execution-wise strictly identical to mine
The compiler might even elide the unnecessary assignment to itself
the simple solurion is
Color col = Color.black;
ColorUtility.TryParseHtmlString("", out col);
Nope, as you need to assign all the out variables in a method before returning it will overwrite it with some default value (which might not be black), even if the method returns false
interestingly it return Color.white if it fails, I had expected Color.black
Hah weird, I expected transparent (RGBA all to 0)
tbh, that would make much more sense, chalk it up to yet another Unity anomaly
I'm having issues teleporting the player to a specific position, I'm using the StarterAssets Third Person Controller unity package.
ThirdPersonController.cs: https://pastebin.com/WGnskBWY
GameManager.cs:
using UnityEngine;
using StarterAssets;
public class GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
public Room currentRoom;
public Room startingRoom;
GameObject playerFollowCamera;
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(gameObject);
}
}
private void Start()
{
playerFollowCamera = GameObject.FindWithTag("PlayerFollowCamera");
SetRoom(startingRoom);
}
private void UpdateCameraBounds()
{
CustomConfiner confiner = playerFollowCamera.GetComponent<CustomConfiner>();
CameraBoundsCollider bounds = currentRoom.GetComponentInChildren<CameraBoundsCollider>();
Debug.Log(bounds.transform.GetComponent<Collider>());
confiner.m_BoundingVolume = bounds.transform.GetComponent<Collider>();
}
public void SetRoom(Room newRoom)
{
currentRoom = newRoom;
ThirdPersonController.Instance.transform.position = currentRoom.spawnPoint.position;
UpdateCameraBounds();
}
public void ChangeRoom(Room newRoom)
{
// Get the door that has as destination the current room
Door[] doors = currentRoom.transform.GetComponentsInChildren<Door>();
foreach (var door in doors)
{
if (door.destination == currentRoom)
{
ThirdPersonController.Instance.transform.position = door.destination.spawnPoint.position;
break;
}
}
currentRoom = newRoom;
UpdateCameraBounds();
Debug.Log("You are now in " + currentRoom.name + ". " + currentRoom.description);
}
}
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.
Just doing a quick glance it looks like your if statement is checking if door.destination matches the room you're currently in and not the room you want to teleport to?
I hesitate to speak authoritatively on that though, it's just something that caught my eye that I wasn't sure was intentional
Oh sorry for not having stated it out, I'm making a room system, where I can move through doors, and it basically should teleport the player to the new room spawn point
But that doesn't happen
The UpdateCameraBounds works
And in general the teleport system works, but the ThirdPersonController is not being teleported
I even tried to disable the Char Controller while doing the position change but nothing
Stormcaller is correct.
this
if (door.destination == currentRoom)
{
ThirdPersonController.Instance.transform.position = door.destination.spawnPoint.position;
break;
}
looks like it teleports to the current room
But it doesn't happen in game
And if I try to freely move the position of the ThirdPersonController from the Inspector it does move
So it's not fixed in place
in this code
if (door.destination == currentRoom)
should currentRoom not be newRoom
But the door in question has as destination the room that I'm currently in, so its the Door of the other room, should be correct
but you are checking destination, it makes no sense for the destination to be the current room
Oh actually sorry, that foreach was for teleporting me to the position of the destination door, not the destination room
It could be simplified now
But it still should work i guess
Cause I have redundant references, Door A-Destination Room B and Door B-Destination Room A
still makes no sense. it's saying I'm in room A and I want a door destination == room A
Shoot, i forgot to change this:
Door[] doors = currentRoom.transform.GetComponentsInChildren<Door>();
to this:
Door[] doors = newRoom.transform.GetComponentsInChildren<Door>();
now it makes sense
Damn still it doesnt update the position
but at least it goes in that if statement now
so whats happening now instead?
I was recently told by someone in here that continuous collision detection still works with colliders set to trigger, but this still keeps happening ("This" being that the collider keeps phasing through the wall as if it's doing discrete detection). Was I lied to or am I doing something wrong?
the wall has a trigger?
it should work
how are you moving the sphere
just to be sure , triggers are not solid so its going to go through anything
No, just the sphere. The wall doesn't even have a rigidbody
Yeah, the wall's collider is not a trigger
but a trigget + rigidbody will not be stopped by a collider
I'm simply setting the sphere's velocity every fixed update
well the ball is trigger so its going to go through the wall
Does anyone know how to put a png on a material?
Ah. That's my mistake. What I did was I put a statement on the sphere's OnTriggerEnter event that's supposed to tell me that the trigger found something and it's not firing
drag and drop
replace the .mainTexture property
yes it Should be firing when hitting the wall then
It's not hitting the wall, though. It's going through it
correct the ball is not solid
it should still call a trigger enter from the ball though
No, I mean it's going through the wall so fast that it's not even noticing the wall is there
how fast are you moving it though
None of the frames have the sphere touching the wall
void Update()
{
GetComponent<Rigidbody>().velocity = Vector3.forward * 200;
}
void OnTriggerEnter(Collider other)
{
print("Trigger connected");
}
void OnCollisionEnter(Collision collision)
{
print("Collision connected");
}```
I deliberately ratcheted up the velocity to something absurd specifically to test this
does it work at lower speeds?
200* shouldnt be too bad with Continous on, but I never tried with trigger . Uusually my ball/bullet is solid
Yes, but that's because there are frames where the sphere is intersecting with the wall at lower speeds
try changing Update to FixedUpdate perhaps? might help, might not
I tried doing that, too, but I ran into the problem of the bullet transferring force to the target and I don't want that. I don't want anything the bullet can hit to be kinematic, though, and if I make the bullet itself kinematic then it doesn't detect collisions at all
It doesn't
if you have at least 1 dynamic rb, Kinematic does fire triggers n collision events
maybe for real fast speed you're better off using casts
I want to avoid that since I don't know how I'd write my own cast function without making every bullet have the same kind of collider
For what ever reason putting a rigidbody on the wall makes the bullet go through even if I set both to continuous detection and make them both not triggers
if i want to save a custom type, ie. item to a binary file, how would i do that since binary can only store floats, strings, bools, and ints?
item holds a bunch of other values
that is not true, binary can store anything, that is, after all what the internal representation of EVERYTHING is
the wall should not have rigidbody in the first place
oh, i was watching a tutorial and they said it can only store those. Ig not :p
idk much about binary
my guess is the speed which you are passing might be a bit high for the physics to keep up.. casts are very easy to do
that's rather odd considering the fact you want to do game dev
i came from godot, and instead there u didn't use binary for saves
How would I do it without forcing all similar object types to use the same kind of collider, though?
so i never got around to learning binary
That's the thing keeping me from wanting to do that
what does collider have to do with it exactly
Because I'd have to be able to cast different kinds of colliders
Unless I just made them all the same type of collider
you're not casting the collider but shapes eg, a sphere or box or line
if you want specific collider shape there is also SweepTest https://docs.unity3d.com/ScriptReference/Rigidbody.SweepTest.html
Yeah, and they'd have to all be the same shape. How would I be able to have one script handle different shapes even ones that aren't technically supported (for projectiles that have mesh colliders)?
i also trust bracheys knows what he'[s talking about
but ig binary can store more
not at all, lol, he probably knows just a little more than you do
ah ok
so i can save any type to binary?
yep
that makes it so much easier
it's called binary serialization and it's pretty simple, the trick is in the serialized format
do you have any resources? since ig the bracheys vid isn't the valuable if there is wrong info in the first 5 mins
tbh no, I wrote my own serializer many years ago and I don't do tutorials
ah T-T oh well
well mesh colliders arent typically used for physics unelss its set to convex
unity no longer supports concave physics unless its kinematic afaik
Which turns it into a cube anyway, right?
not a cube necessarily
But that's where your Rb.Sweep function would come into play, right?
if you want to test colliders / rigidbody with mesh collider at all
Rb.SweepTest supports whatever colliders dynamic rb does
not performant at all but convex shapes are part of it yes
So it's entirely possible to use this function as a catch-all cast for any kind of projectile I want?
I never seen bullets that need some type of pin point accurate shape
its a good backup imo but you dont have to use that as the others work fine such as raycast or spherecast etc
primitive shapes generally work fine, not sure why you'd need anything else
I'm mostly looking to avoid having to make different handles for different primitive shapes
Something about that feels really messy to me
people make bullets round sphere or capusules when in reality they are more cone shapes
I was more thinking box colliders for things like crescents, but it just feels weird having to put a box collider on a perfectly spherical mesh
like this you mean ?
Yes
Spheres are also easier on the physics engine, to know whether a collision occurred it just asks "is this object in that radius at this position"
Since a sphere can be represented by only a position and a radius
yeah you're gonna have to compromise some imprecision for performance
Alright. I can live with that. I suspected that might be the case, but it's really helpful just having someone explicitly tell me that
its not like unity would support that shape as mesh collider (w rigidbody ) without it being convex
which will then make it a weird half sphere thingy
more you can do with primitives the better for the engine to deal with.
casting a bit more forward than its move direction is good enough imo, you probably dont need the curve for anything but visual
@spare dome I do not think Codist has any AI stuff. Should be able to run entirely offline
alrighty, i searched up Codist AI and there another thing like that
this isnt the same right?
https://github.com/autosoft-dev
yeah, that is a different project entirely. different dev too
I am struggling to find ways to order my code to appear to run simultaneous even though internally, it is sequential. For example, if I have two players that I want to update each frame, I would normally write something like this:
playerOne.UpdateLogic();
playerTwo.UpdateLogic();
Now, lets say I have logic for each player to cast a hitbox that sends the other player into a hit stun state after being hit. In this scenario playerOne would first hit opponent and force playerTwo into the hit stun state. Afterwards, playerTwo’s logic would run, but since playerTwo got put in hitstun, so her hit boxes disappeared. Instead of both players exchanging hits and being put into hit stun, only playerTwo is due to playerOne preforming his logic first.
For this specific situation, you may advise me to simply update the players’ hit stun at the end of frame like so:
playerOne.UpdateLogic();
playerTwo.UpdateLogic();
playerOne.UpdateHitStun();
playerTwo.UpdateHitStun();
Which is all fine and dandy, but we have another situation that can cause problems: players can move around, possibly dodging the hit boxes. If a player moves out of the range of the hit box at the same frame that it is cast, it will produce different results from player to player. If playerOne casts the hit box, the hit box will hit, as playerTwo’s movement has not been updated yet. However, if playerTwo casts the hit box, the hit box will miss as it has not been updated yet.
We can put a bandaid on it by having another method to run in the update to check the hit boxes like so:
playerOne.UpdateLogic();
playerTwo.UpdateLogic();
playerOne.CheckHitBoxes();
playerTwo.CheckHitBoxes();
playerOne.UpdateHitStun();
playerTwo.UpdateHitStun();
This method quickly becomes cumbersome. Each time we make these methods, we have to route our player code to wait for this method, which makes it frustrating to work with and messy. Does anyone have advice on resolving this issue? Thanks!
Have you never heard of Arrays?
Yes.
would you like me to iterate through action arrays?
well
Queue<Action>[]
would seem to fit the bill
anytime you find yourself writing something like this
playerOne.UpdateLogic();
playerTwo.UpdateLogic();
playerOne.CheckHitBoxes();
playerTwo.CheckHitBoxes();
playerOne.UpdateHitStun();
playerTwo.UpdateHitStun();
A red light should go off in your head that you are doing something wrong
I know, it was an example.
So specifically, you want me to load an array of actions, iterate and invoke them?
not exactly, you can load a Queue of Actions for each player and then you can control the execution of those Actions by Dequeuing at a time of your chosing
Not sure I follow. Can you write a brief example?
Also, isn’t a queue a collection? Why would we need an array of them?
one for each player
Array is per player
Queue is the player internally
I see. But shouldn’t I make players hold their action Queue in their own class so that the player’s UpdateLogic can determine what is in the Queue?
Well, I’m try it. Thanks guys!
Oh I thought I answered this, anyways, I fixed it by storing the player transform, disabling the whole ThirdPersonController script, editing the position, enable the thirdpersoncontroller script
If i copy an array, like a vector3 array, then it places a super long string into my clipboard, like this one:
is it possible to generate that paste-able string during runtime so i can copy vector3 arrays from during runtime and directly paste them into vector3 arrays inside the editor?
How are you copying it?
Right Click an array > copy
In the inspector?
Copying data in the inspector uses it’s own data serialization.
I would suggest using json serialization instead for something in runtime, but I’ll try to find the method to get the inspector string
what would be the usecase for this exactly , I'm confused on that
you mean like make a Vector3 array as Json ?
I want to generate an array of Vector3's during runtime, then copy them into my clipboard so i can paste said array into the editor.
Oh just generate a string from json serialization no?
Nah he wants specifically wants the EditorGUI string
Yes.
ohh ok
Optimally i would want it to just be a right-click > paste into the editor.
But if it uses a special Serialisation, that's fine, i could think of other methods.
I am pretty sure it holds more data then just converting the property to a json is the problem.
Otherwise you could just use a json serializer.
they only mentioned v3 so I was confused
Could i write a script that generates a json object of the vector3 array, copy that json during runtime, then in the editor paste the json into a string, then when i run the script once, it turns the json object of the vector3s into a serialized array that i can then paste into the originally intended array slot?
would be tideous, but it would work, right?
its going into another array of v3s?
Just make the script parse the json from the file. Don’t use an inspector property for a json string lol.
Can't i turn a string into a json object?
well yea
Hm. Then let my try that tideous method!
why is the json needed at all, can you just write script that targets that specific component ?
Yes… but don’t use that string un the inspector.
iirc unity has a script example on the Cinemachine component that uses a method of saving runtime values to a component in playmode
Eh. Json is a good file format for saving data.
I can only generate the v3 once i build the scene, and once i build the scene i lose access to the inspector.
you shouldn't need the inspector if you target that specific component in code no? Just have the reference
if its part of the scene ofc
That's not the issue tho...!
I want to grab the v3 array i generate during runtime, and then place it into a v3 array in the editor.
yeah I get that, but v3 array is on a component yes?
Why do you want do to this again?
i'm guessing to save the runtime values to have the object start with those values on next run?
yes!
Yes!
right. So just feels like serializing to json then deserialize is an extra step if you just target the specific component you want to apply the changes to
here is how unity does it for the Cinemachine component I mentioend
so like any changes made on that component persists when game is stopped
its a bit advanced to study though, so maybe json might be easier.
Hm. I'm gonna try something here! I'll let ya know if it worked! Thank's alot for the help :D
sure thing . goodluck!
ty!
you know it is so easy to convert an array to a byte array and save it to, for example, a memory stream, then convert the byte array back to it's original array form
save all that pointless messing around with json
interesting, how do you utilize the runtime memory stream once when the game is stopped and use it on component?
Ah, if you want to preserve it over domain reloads, then use a file stream or, better, a memory managed file
oh does stopping game trigger a domain reload?
the editor is a different domain than play mode, yes
from my understanding they have
ScriptA => Runtime Generates say Array "a","b", "c"
stop the game
ScriptB Array=> ValuesFromScriptARuntime "a" "b" "c"
there are lots of options, saving to json is probably about the worst you could chose
hah yeah this stuff is def beyond my paygrade. I'm sure you can offer a better suggestion here lol the Cinemachine one is more convoluted cause of that reflection looking stuff
yep, so that has to cross domains, so you need a file store, like a memory managed file which can do that
you could use named or anonymous pipes to effect the same thing
seriously complex stuff, probably way too complex for him
haha yeah also for such a simple usecase it might be over-engineered tbh
true, but a useful construction to know, it can be used in many cases
indeed! TIL for sure
eh this is a coding channel, might be better off asking in #⚛️┃physics or #🏃┃animation maybe #💻┃unity-talk
if you do a lot of Editor tooling it's nice to have a communications pipeline between Playmode and the Editor itself
Yeah I need look into those, rn just doing the basic UIToolkit stuff but soon will try to make a level editor with splines for my Shooter template, and I might need deeper control for placing nodes n stuff
plan on having the user able to easy make levels / pathways for game mode by using editor tooling 
Yo , i have a problem with a game
probably in #💻┃unity-talk
does not seem code related
it is not, this is a discord for Unity Developers, not games made with Unity Support
Ooh ok thx
look up reptilehideout I believe thats the discord
cant send invites here or it auto mutes me 🙂
Ok thank
How do I play an animation clip in reverse in timeline..? In the AC I could set the speed to -1 but I can't seem to to that in the timeline clip inspector
Oh.. you can't. 😐
yeah unfortunately this animation clip (on a 3d model) was.. created by an external shop and has a keyframe every frame
i hate -1 speed cause it messes with my transitions
I was just gonna try that.. copied and pasted the .anim and was gonna .. just move everything around, but it seems like a huge pain
same
😦
hm.. i'll try.. i'm thinking I'm gonna F this up somehow
make a clone ofc
ya
😉 spend 30 minutes creating a script to do this for you instead
obviously i have version control lol
just saying, this looks to be like one of those super fiddly type things where you ... mess up one keyframe and then you gotta roll back 5-10 minutes of painful clicking and moving these things around
this model has a looooot of animated vertices
save and commit before you do this
if its something you need to do often, creating an editor script for this actually might be better
ok that was actually not painful at all and worked great
select all the nodes and there's a node at the top of the keyframe editor that just magically selects all of them
so I moved each node to the right (from the back, reversing them), then moved all back to 0:00
MoveIn, Move x 3, MoveOut
MoveOut is the new one I just made
ahh timeline, i should probably start using that
Yeah I'm ... debating whether I want to.. the way I understand it is that it's not compatible with animator controllers, which was how I was gonna manage my FSM for these guys
but timeline will let me do things like compose "a move" (ie, idle -> movein -> move x3 -> attack x2 -> idle) and coordinate it all with cinemachine vcam cuts, particle effects, sounds, and so on... doing it in code via dotween sequences has been tedious in the past for me
ie, 500 lines of code to do like.. a reward box opening
Really fun character 🙂
Is it an underweight chinchilla or something?
Hey im curious on how i would handle possible tens of thousands of zombies in a 2d open world game
for (int i = 0; i < 10000; i ++) Instantiate(zombiePrefab);
Idk if dots is what i need since i dont need many zombies on screen
And if that's slow.. google up object pooling
You probably don't need dots, but you probably will need/want object pooling
Im not a beginner i understand how to spawn them and object pool
Im asking if its going to be sufficient
Like should i make a system where instead of having thousands of game objects
Just keep a track on where they are and despawn them when out of range?
If you're not a beginner.. you should understand why that question is kind of impossible to answer.
It depends on the game objects and how much of the CPU and GPU they're gonna need on each tick. Physics? Colliders? AI? Textures? Lighting? 2d? 3d? There's just too many things that go into an answer like that..
no one can asnwer that but you, we dont even know what type of assets you have
Yea my bad ill explain
many things affect performance including code
They are just 2d sprites with animations and they will have ai functionality to follow and attack the player using pathfinding
So.. I mean, I get sorta what you're asking, but your question is too broad. If you have 20k zombies in your open world game and you're concerned about rendering them, then you'll want aggressive occlusion culling, clipping planes, and level design so you can't see that many at once.
If you're concerned about pathing and CPU and AI, then you should probably only be doing AI updates when a player is within range.
you can also do the pathing calculation in seperate thread if you're not using specific unity apis
If they're ALL sorta moving toward the player then you'll probably wanna chunk them up and give the same pathfinding to chunks of them - ostensibly zombies that are far away are all moving in roughly the same direction, so calculate that direction once and then apply that logic to each of those 500 zombies (or whatever) in that far away "chunk"
Im basically not sure myself on what would be the biggest cost on performance
Well we aren't either, and you won't know until you build it and profile it 😛
thats why we just make it, and profile. optimize as needed
Might be GPU.. might be CPU, might be boneheaded pathfinding applied to 20k units.. etc 😛
nava timeline is awesome btw
check out how easy this is to string together animations
I used to have a script on each of my coins rotating itself, turns out it was better to only have 1 script controlling all coins rotating
if I did that in tweens.. god that'd take forever
Yep definitely
and the animations have the blending support animationcontrollers have
way better than trying to do that in code and work out all the timings
but isnt this better for like cutscenes not soo much going into specific states like animator or am i misunderstanding ?
yeah but .. I'm thinking the way I'm gonna do it is have mini "cutscenes" for something like a "move and attack" turn
look good though 😛
Reminds me of this book I read when I was little (although yours looks more cynical lol)
the only real animation controller I think I'll be needing is just to set characters to idle
or maybe I'll use the signal emitters in timeline.. i dunno yet
Trying to figure out a way to make a timeline that's usable for multiple characters + .anim clips for each
dunno if I can do that since each animation clip refers to the meshes verticies by name, and they're not the same obv.. like if I drag one "move" clip from one character onto another animator in timeline, it doesn't do anything (obviously)
I think maybe the way I'll do it is.. make a timeline for the attacking character that has a signal track (which emits a signal when it does damage?) and then the uh.. playable director? fills in the details at runtime
Can anyone help me in #archived-lighting ??
Wait does dots work with any networking solution?
is it possible to intercept the delete event from editor so i cannot delete a gameobject in the scene? i specifically want to prevent deletion of child objects of the parent, because if i do that by mistake it breaks stuff
that way they only delete if i delete the parent
I override it
public class BetterMonoBehaviour : MonoBehaviour
{
protected new void Destroy(UnityEngine.Object @object)
{
if (@object == null) return;
if (@object is not GameObject)
{
Assert.IsTrue(false, "Inadvertently using Destroy() on a component instead of a GameObject.");
}
else
{
try { UnityEngine.Object.Destroy(@object); }
catch
{
// unlimited power
}
}
}
}
I inherit from my "better" monobehaviour class everywhere so I don't accidentally do something simliar - accidentally delete a component from a gameobject (which I basically never do) so I don't do it by accident
you could just basically do the same - new your Destroy method and just have it do nothing or whatever
I only know netcode does, not sure about others
https://docs.unity3d.com/Packages/com.unity.netcode@latest
interesting, thanks!
Would hate to have to learn unitys netcode now 🥲
what else would you use? ECS is already a complex system, add netcode and yeah it gets complicated fast..
kinda jumping the gun if you havent profiled anything yet and just going on assumption
they're all pretty much the same (for gameobjects)
just different flavors
no it doesn't. for dots you need their ECS specific netcode
Hey y'all, I've got a video for this one... essentially, the music works the first time you run it +until you pause, after pause, the music just... doesn't play. The home button runs this code and this code:
public void resetter(){
settingsIsActive = false;
}
public static void ReturnHome()
{
SceneManager.LoadScene(sceneMap["Home"]);
Time.timeScale = 1;
}
and my pause works like this:
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
settingsIsActive = !settingsIsActive;
AudioListener.pause = settingsIsActive;
settingsUI.SetActive(settingsIsActive);
if(settingsIsActive)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
Debug.Log(Time.timeScale);
}
So it shouldn't be a timescale thing, should it? It also claims the music is playing for one frame on every refresh, as every time I run it the "music playing?" log goes up by 1, but it cuts out immediately afterward. NOWHERE ELSE IN MY CODE are stop or start mentioned for audio. What is going on???
relevant code to "music playing":
public void TerminalButtonPress(){
if(phase == Phase.OPEN){
theMusic.Stop(); //this didnt matter before, but it totally does during resets w pause button
theMusic.time = 0;
theMusic.Play();
playing = true;
noteScroller.started = true;
Debug.Log("music started HERE");
}
else if(phase == Phase.CLOSE){
levelSummary.SetActive(true);
}
}
``` (runs when you click that button)
..also the homescreen doesnt even HAVE an active settings manager (pause menu), so it again, really shouldn't be doing this.
private void CheckGameOver()
{
Debug.Log("health " + healthBar.value);
Debug.Log("settingssss?" + SettingsManager.instance.settingsIsActive);
if ((healthBar.value == 0 || (!theMusic.isPlaying && playing)) && !SettingsManager.instance.settingsIsActive)
{
gameEnded = true;
EndGame();
}
}
code to check if game is over, it always returns true here because !themusic.isplaying
But i don't know what's stopping it... I've been stuck on this for a week, any help would be extremely welcomed
Try setting timescale to 1 BEFORE loading the scene
Doesn't change anything.
You are setting AudioListener.pause when pausing
So should I set it to false in my reset function?
https://paste.ofcode.org/8biXBq89vaKcHZRVJ38Wqe
externalVelocity: the velocity/float/bob of a moving platform. I apply this to the player's velocity so they move around with the platform.
I know input/movement framerate independent; Have I multiplied TIme.deltaTime correctly? Do multiply by this many times?
Do I apply velocity.y += gravity * Time.deltaTime; every frame or just when the player is not grounded?
Do I call a second Move() to apply apply gravity/external velocity after my initial Move() call?
The player applies downwards force when landing on platforms. Do I even need to smoothing externalVelocity? I want to avoid jitter.
Yes, it's a global value, so you need to take care to properly reset it
alright, gimme a sec, wrote some print statements too
That fixed it. Bless you.
dont crosspost #854851968446365696
@lean sail Sometimes, I dream about cheese
dont @ me on useless stuff either please.
@lean sail okay
I'm just brainfarting this afternoon.
How can I create a Vector2 tween for position from X to Y with a starting velocity? essentially a tween with an ease like InExpo but with a starting velocity that isn't 0.
The use case is missiles animating out of a gun. Bonus if the missiles track the target in case it's moving.
I'm assuming I might have to bust out ye' old lerp and do something from T = -1 to 1, but play it from 0 to 1 (with DOVirtual.Float)
@modern creek
https://chicounity3d.wordpress.com/2014/05/23/how-to-lerp-like-a-pro/
As you said, one way is Lerp. Follow the link for dynamic Lerp effects.
Yeah was just hoping to use DOTween's API but.. I can't find an easy way to tween from 0-1 but start at 0.5
I'm currently doing 0-1, dividing by 2 and adding 0.5, and starting from the inverse vector of the target, but ... the effect isn't the same
void Update() {
//reset when we press spacebar
if (Input.GetKeyDown(KeyCode.Space)) {
currentLerpTime = 0f;
}
//increment timer once per frame
currentLerpTime += Time.deltaTime;
if (currentLerpTime > lerpTime) {
currentLerpTime = lerpTime;
}
//lerp!
float perc = currentLerpTime / lerpTime;
transform.position = Vector3.Lerp(startPos, endPos, perc);
}
}
1 second let me check
I've never used DOTween before tbh. I perfer this native solution./
yeah.. I know but I like DOTween because I can chain together sequences and so on easily.. I might just have to manually lerp it and do the other stuff in parallel
i also was hoping to not get into the business of mathing up all the easings I want - lerp is actually almost never the right one for animation
Yeah I'm gonna have to come back to this when my brain is fresh, I have all kinds of bugs going on here
public void OnFireMissileStart()
{
Sequence seq = DOTween.Sequence();
Missile.transform.localPosition = _missileStartLocalPosition;
Vector3 missileStartPosition = new Vector3(
(2 * Missile.transform.position.x) - MissileTarget.position.x,
1f,
(2 * Missile.transform.position.z) - MissileTarget.position.z
);
seq.Append(DOVirtual.Float(0, 1, MissileFlightDuration, x => SetMissilePositionInstant((x/2) + 0.5f, missileStartPosition)).SetEase(Ease.InExpo));
seq.Play();
}
private void SetMissilePositionInstant(float progress, Vector3 missileStartPosition)
{
Vector3 position = missileStartPosition + ((MissileTarget.position - missileStartPosition) * progress);
Missile.transform.position = position;
}
@modern creek
static DOTween.To(getter, setter, to, float duration)
Have you attempted just Lerping the duration? (In which case u might as well Lerp the whole thing)
that's basically what I'm doing with DOVirtual.Float
but.. I think I'm just having some dumb re: the starting position and so on
I've never used this Library b4 sorry I'm not of much help
I was thinking the missile start position would be the the target "in the opposite direction" and i'd lerp it from 0.5 to 1 but... I think I'm just overcomplicating this and there's an easy solution I'm not seeing atm
no worries - it's just the same as what you proposed, just imagine DOVirtual.Float is the same as Lerp
already I see one problem that I'm calculating the lerp position based on the target position - which can change over the lerp.. so if the unit is rotating while firing missles (ie - the target is moving), then the missiles in-flight are gonna go flying all over the place
anyway, will fix tomorrow, thanks for your eyeballs 👀
👍
Im currently moving a gameObject to a specific distance away from the direction that the player is moving. Does anyone have any ideas on how I can make the selected part collide any object it hits, not allowing it to move through them?
This is the code that I am using to move the gameObject
selectedObject.transform.position = Vector3.Lerp(selectedObject.transform.position, player.cam.transform.position + player.cam.transform.forward * partDistance, Time.deltaTime / 0.075f);
setting transform position directly will completely ignore colliders
Is there any way to move the part without transform allowing it to collide?
how do you normally move it?
I move it using the transform to the direction the player is facing. I can send a longer code block of my entire function if required?
Move the object via the Rigidbody not its transform
Okay thanks
Hey, completely forgot to mention this one. I need my gameobject to be able to move within a 3d space. Currently I am disabling the isKinematic property of the rigidbody whilst I am moving it with my previous method. Would this still work?
Sorry for the late response, I got preoccupied with other matters
Of course you want it to move in space, what else were we talking about???
No your previous method of moving via the Transform will not work
To get proper collisions you need a non-kinematic Rigidbody and to move it via setting velocity or applying forces
My bad, I thought it would react to gravity
Gravity is a separate topic and not really related to the current discussion
there's a separate checkbox for gravity
Yeah I got that now 😆
Anyways, I'm trying to move it to the specified location whilst colliding with any other object. This means that it would not move to that location. I attempted something like this with the RigidBody.movePosition method, and the physics do collide however the part is still able to clip through other parts. (My intentions are to remove this clipping)
Sure as I said you need to move it with velocity or forces
Everything else will not respect collisions properly
ahh- I'm pretty new to everything, I apologize. Thanks for the assistance.
I'm trying to get the country in the script using this line of code System.Globalization.RegionInfo.CurrentRegion but it give me the wrong country name on browser
https://cdn.discordapp.com/attachments/1178165436861390849/1272418559170969614/20240812-0456-25.4429610.mp4?ex=66bae7a0&is=66b99620&hm=2e5b850d6f91b7637bf6c60c9e686c846b682f96826070fa0a7cd3a4d171e2e5&
I have an issue with adding torque to this circle to go to my cursor, sometimes it decides to go the much longer way instead of the shorter way
public void RotateSword(Vector2 _mousePosition)
{
mousePos = playerCamera.ScreenToWorldPoint(_mousePosition);
playerToMouseDir = ((Vector3)mousePos - transform.position).normalized;
if (swordRb.rotation > 180) swordRb.rotation = -180;
if (swordRb.rotation < -180) swordRb.rotation = 180;
neededRotation = Quaternion.FromToRotation(playerToMouseDir, swordRb.transform.up).eulerAngles.z;
if (neededRotation > 180) neededRotation = -(360 - neededRotation);
swordRb.AddTorque((-neededRotation) * Mathf.Deg2Rad * torque);
}
maybe just an issue of the slow acceleration but im not sure
if i could get it to stay rotating in the same direction instead of slowing down and changing direction that'd be epic
this code looks kinda unnecessary, couldnt you just this to get the angle? https://docs.unity3d.com/ScriptReference/Mathf.LerpAngle.html
Also not really sure what you want, it doesnt actually look like its taking the longer way to me. This code doesnt care for the current torque but you'd need to factor that in if you actually wanted it to choose which direction to go based on what would be faster. Do you actually need it to rotate with torque here, where it ramps up in speed? If you could just rotate it directly, that'd really simplify things here
I think we want it to use torque so we can push stuff and we want it to like affect the players movement
I'm not the one who who's writing the code for it so I don't know the exact reason
I think rotating directly would cause issues with a rigid body no?
we also need the sword to have a weight and momentum
the goal is to have a physics based sword that orbits the player and the mouse influences where it is
the sword needs to have weight and momentum and needs to keep the current behavior where the momentum of the sword actually causes the player themselves to move
like how in getting over it you control the hammer
we want it to work pretty much like that but top down
Might still be easier if you just directly set the angular velocity so you dont have to worry about that whole slowing down thing. Either that or apply more torque if it's the opposite direction.
hey there peeps! How would you approach this? I guess some shader black magic would be the best option but i want to get your opinions:
I have a plane gameobject A with a color, lets say yellow. And I have another one B with another color, lets say blue.
So I want that when they both overlap, the overlapping section changes to green, and I can even add text on it.
What would you suggest there?
The colour change onoverlap sounds like a job for a Tri-Planer shader, the 'adding text' should be doable with standard TMP
ill research that, thanks!
unity and Catlike coding both have decent tutotials on that which should help, the catlike coding one is very good
Hello. Can this code be used as a benchmark for comparing the execution speed of two pieces of code that do the same thing in order to find the faster (better) one ?
void Start () { Stopwatch timer = new Stopwatch(); timer.Start(); for (int z = 0; z < 10000000; z++) { //Some code here } timer.Stop(); UnityEngine.Debug.Log(timer.Elapsed); }
There are some posts online about C# benchmarking which describe the process in detail
Here's one I've read a while ago:
https://www.codeproject.com/Articles/61964/Performance-Tests-Precise-Run-Time-Measurements-wi
How the .NET Framework Stopwatch class can be used to measure and compare algorithm runtime with a high accuracy
Hey so im following this tutorial ( https://youtu.be/9fa4uFm1eCE ) but when i enable my renderer feature only the ui is being rendered and i get a black screen
Inspired by the release of Hi-Fi Rush by Bethesda, I wanted to see if I could get a similar vibrant and stylized aesthetic in Unity. Little did I know, it would swiftly lead me down a rabbit hole of custom rendering in Unity and, in turn, completely overhaul my entire perception of Unity's Scriptable Render Pipelines. This video is a showcase of...
hey guys, i have a code for loading a scene from addressables and for unloading it, the loading part works just fine but when i try to unload it doesnt work, i think the code is not successfully saving the scene in a scene instance for some reason
void ExamSceneOnAddressableInstantiated(AsyncOperationHandle<SceneInstance> handle)
{
if (handle.Status == AsyncOperationStatus.Succeeded)
_examSceneInstance = handle.Result;
}
public async void OpenExamPanel()
{
examSit = true;
//Screen.orientation = ScreenOrientation.Portrait;
//MasjedScreenPanel.SetActive(false);
//JoisticPanel.SetActive(false);
//ShowRRoomPanel = false;
//SceneManager.LoadScene("Rashidi");
await Task.Delay(2000);
OpenCursor();
this.GetComponent<AudioSource>().Stop();
Addressables.LoadSceneAsync("Exam", LoadSceneMode.Additive, true).Completed += ExamSceneOnAddressableInstantiated;
//SceneManager.LoadScene("Exam", LoadSceneMode.Additive);
}
public void GotoMasjed()
{
//Screen.orientation = ScreenOrientation.LandscapeLeft;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
//gameManager = GameObject.FindGameObjectWithTag("GMScript").GetComponent<GameManager>();
///gameManager.MasjedScreenPanel.SetActive(true);
///gameManager.JoisticPanel.SetActive(true);
//thirdPersonActivate = true;
ThirdPersonController.thirdPersonActivate = true;
SingleThirdPersonController.thirdPersonActivate = true;
//SceneManager.UnloadSceneAsync(3);
Addressables.UnloadSceneAsync(gameManager._examSceneInstance, UnityEngine.SceneManagement.UnloadSceneOptions.None, true);
//TestRelay.StartGame = false;
//GameManager.ReturnFromAmma = true;
//InAmma = false;
//FromAmma = true;
}```
this code is in 2 files
the firsrst which has the first 2 functions which is called gameManager
thats why in the GotoMasjed function it calls the instance from gameManager
I am trying to create an Orbit Origin Based movement rotation. I want to keep the old X and Z rotation in the **local axis **of a GameObject but change the Y in the local axis dynamically. The Orbit Origin currently changes the X and Y properly but i don't know how could i achieve the Y axis rotation without having problems with gimbal lock.
The locking should work with one axis too. Likely, by locking only local X, i should be able to change Y and Z.
https://hastebin.com/share/aqazuqidax.csharp i want it o just instantiate once but it just doubles every time
Hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You have the script on two objects or twice on one
no i have it on only one object
i checked
Debug.Log("I am on " + name); <-- put this in Start
Hello. I have started Coding the Meta-Part of a Mobile F2P Game. I am implementing this for the first time so just wanted to ask which pitfalls or mistakes to avoid and if there is a Good tutorial for it.
Hello, i need a little help with something!
Im working on UI for my game, and it requires me to instantiate new buttons sometimes. These buttons should call a function with an int parameter based on which button is pressed, i want to assign a function + a parameter to a button when it's created. My question is: how do i hook up a function with a parameter to a button via a script?
Im basically asking how to configure this part of a button from a script
The new scripting API documentation harder to search from outside now https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.Button.html#UnityEngine_UI_Button_onClick
That worked, thanks a ton
acutally, there's a problem. All the buttons call the function with the same parameter, but i need them to be different for each button
i have six buttons, and no matter which i press, it calls a function with a 6
Even tho im adding buttons in the for loop
I am using the Localize String Event component to set up my localized TextMeshPro, but in editor I still have to give it some text that will later be replaced.
Is there a better way? Am I misusing the component? What do you write in the text of the TMP?
Okay, that helped, thanks!
Help i cant set properties in a Unity Custom Editor,
More in Thread https://discord.com/channels/489222168727519232/1272146985608151074
don't crosspost.
So... I need some help...
How is "this = bull ref" a thing? The object is in the hierarchy so nothing is really destoying it. I am very confused
and it's not another script trying to call a method without having a ref to the method's owner, it's a response to an event so if the method is getting called it means that the owner listened to the event (which means it exists to listen no?)
sounds like you are subscribing to events but not unsubscribing
OMG my dumbass tapped tab after typing "OnD" to put the unsubscriptions on OnDisable and it was in OnDestroy, changed it and it seems to be working. TYSM
hi all, im trying to place an object on a surface and have the up direction be the normal of the raycast to find the placement position, and set the forward direction based on the direction the player is facing in
https://youtu.be/N3nzshkuLH4?si=wscRHu-ffAqNZXwu&t=165
I'm looking for behaviour that is akin to this
A detailed guide to the Medium Build's Guardian Turret Specialization and the Heavy Build's Dome Shield in THE FINALS. I look at using them individually and combined.
00:00 Intro
1:08 The Guardian Turret
11:55 The Dome Shield
15:36 Using The Guardian Turret And Dome Shield Together
17:09 Outro
Download and Play THE FINALS here: https://store.s...
i've timestamped the link
this is fairly easy. Whats the problem ?
seems more of a #💻┃code-beginner q too btw
ah rip
(hit enter too early, one moment)
It orients fine on floors and ceilings, but on walls, it sort of sits upright, half in the wall
you'd have to show what you got so far n code
obstructed = Physics.CheckBox(hit.point + placementObstructionBoxOffset, placementObstructionBoxBounds / 2, Quaternion.LookRotation(wm.pc.clientRotationRoot.forward, hit.normal), obstructionLayermask);
hologramInstance.transform.SetPositionAndRotation(hit.point, Quaternion.LookRotation(wm.pc.clientRotationRoot.forward, hit.normal));
ill grab a screenshot of what it looks like in the game
on the floor, its valid and can be placed, facing the correct direction
On the wall, it does this
the biggest bit Im having trouble with is the obstruction box rotation
no idea what wm.pc.clientRotationRoot.forward is
also what's the value of placementObstructionBoxOffset?
you're offsetting in world space, but that value sounds like it should be local space or it wouldn't make sense 🤔
that's a valid point, thanks
I've gotten the direction stuff I wanted, i'm projecting the player's view direction against the plane im placing the turret on and using that in LookRotation
just need to orient the placed turret to match now :p
did you get it working ? curious about this myself now :p
I did, yeah :D
I'll share the code in a sec
I was making a project with lasors + mirrors, I use right click to rotate but using the players view might be a better fit :p
Quaternion rotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(wm.fireDirectionReference.forward, hit.normal).normalized, hit.normal);
where wm.fireDirectionReference is a reference to the camera's parent
so you could probably just substitute that out for the camera's forward if it works for you
oh weird I had something similar but it looked strange for some reason
var itemForward = Vector3.ProjectOnPlane(cam.forward, hit.normal);
something.SetPositionAndRotation(hit.point, Quaternion.LookRotation(itemForward, hit.normal));```
im normalising mine, could that be it?
ahh i see let me try that
that was it thanks!
glad i could help :D
So i made this...
Thought that "hey, wouldn't it be nice if people could use Typescript to do stuff in my level editor?"
But jint is JS only and i didn't want people to have to run TSC
So i wrapped it with Jint
and it somehow works
Now i'm wondering if there is some way to automatically generate type definitions from C# types
Considering the exposed stuff will be wrappers
(cause i don't wanna use AllowCLR, cause they could mess up anything)
what should I do if I'd like to use FindObjectsOfType but i'd like to find all objects that instantiate a certain interface?
so use it
are they different scripts ?
maybe change the spawn method and use an interface
ohhh i thought only the direction of the vector mattered... that explains a lot
you would be much better off just storing those objects in a collection of some sort when you instantiate them rather than using any of the Find methods
i'd like to have an interface I can use to make it such that things can be altered on flash, and when I call "flash" i'd like it to iterate through all objects that have a script that uses that interface, and call OnFlash()
oh right.. you would need to look through MB
in that case, ignore my previous suggestion and use an event
ok
time to learn events then ig
just have them subscribe to the event when they are instantiated
events are dopee
is that a c# thing or a unity thing?
c#
just so I know what docs to look at
both
well, its split into a bunch of different files
ill figure it out, thanks for the help
I am trying to achieve a rotation that is driven by the another rotation but stuck at allowing rotation in specific axises like hours. Quaternions are such a hard thing to understand. Could you help me how can i achieve this without using Euler(gimbal lock)?
In the image, the accepted rotation is Y
Hm i believe my mistake was using literal directions. I should use Quaternion.AngleAxis() to rotate around Roll, Pitch and Yaw.
hey, im fairly fresh in ECS and apparently doing something wrong or missing something obvious but after whole day trying to figure it out i finally tried just copypasting tutorial code from
https://learn.unity.com/tutorial/65b3e48fedbc2a611fc291a7?uv=2022.3&projectId=65b3d3cfedbc2a5399ce3740#65b3e534edbc2a598e6ade03
and it works, but only when subscene is loaded into liveEdit. when i untick scene (which if i understand correctly is state of actual build) i get exception:
ArgumentException: We are reading a UnityEngine.Object but the deserialized index is out of range for the given object table.
and warning:
Error when processing 'AsyncLoadSceneJob(VirtualArtifacts/Extra/a0/a0a6776b66c09598ec3fce9838e3620b.0.entities)': We are reading a UnityEngine.Object but the deserialized index is out of range for the given object table.
ig is common issue when dealing with hybrid approach and authoring monobehaviors, but im totally lost on how to register EntityPrefabs outside live edit. Any point to right tut or advice appreciated.
also tried using EntityPrefabReference from docs, similar results with error that AddComponent was used on Entity.Null
You should ask in #1062393052863414313
Got it, sorry
No worries, they will just likely have the best advice
are you confusing it with something else 🤔
my server is passing the time in this stupid string format, I parse to DateTime and then I can get the float from that, I am wondering if I can then subtract Time.time from it and get a delta between the two times
wait Time.time is runtime seconds
whats the purpose here, not sure I understand
parsing the time string to a usable time in unity
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
I dont understand why cant you use datetime directly in unity
where do i ask for help regarding issues i have with my vs and unity?
#💻┃code-beginner
provide all info
because it's a string that looks like this:
yes I understand, but who says you can't use that in unity?
what do you need to do exactly
hmm, I'll try
emm, no
if it were working like this I would have done it so :3
Well show how you parsed it?
I still dont know what you need to do with the time inside unity :p
if you explained the usecase we can probably provide better fix
it's a serializable object!!
and datetime is not serializable as you can see
while my class is serializable, and parses it to a DateTime
How do you serialize a sprite?
I need to be able to use it in a network variable but it won't run through serializer
You wouldn't, not directly. You'd want to serialize only some kind of key or reference for the other side to be able to find the sprite
Hmm, I might have to rethink the way i'm doing it then
What are you trying to do
The other side should know statically what sprite to use depending on the command/choice you send.
So the item object is in the network variable
And it's a scriptableobject so i can create many
So i'd need to serialize all data in it
The only thing i can't do is the sprite
You should just be serializing a reference to this item
An item id or the item name
That's it
Both sides already have the ScriptableObject assets
There's no need to serialize the whole thing
I see what you mean yeah
How would you do that? Would i have to create a list of all scriptableobjects and load it from there?
That is one way to do it
I already have a global items table and each item has a unique name, so its probably the easiest way
Thank you
A dictionary would be faster but sure something along those lines
am i being dumb, i have [SerializedField] on a class that is just a regular plain C# class but the inspector is showing me an inspector element like when its expecting a scriptable object
oh i was being dumb
nevermind
heya, sorry for the package specific question but this one is fairly popular and doesn't seem to have a discord- is anyone familiar with magica cloth 2? I can place my model in their demo scene and it'll work with meshcloth, but the instant I put it in my own scene instead it doesn't work, even though the gameobject with the mesh is 1:1 in both scenes
honestly depends on what you are trying to do with the time. A time "delta" only makes any sense of the two times are related in some way. This datetime could be anything (could be the real life time it was sent, or it could be the time since the server started, etc). Time.time is the time since the Unity application has started, so if it makes sense to make a delta from that, then yes nothing is stopping you from subtracting a float from a float
i'm a dumbass, distance culling was on and my camera was far beyond the limit haha
In case someone interested in this, i ended up using Quaternion's own methods for keeping the same direction with current rotation. I didn't use Quaternion Euler's because i didn't knew the difference until now. Good news, it works like a charm!
I'm trying to make the camera keep both players on screen at all times, zooming in more when they're closer and zooming out with distance, but the stuff I'm finding online is outdated and doesn't work, so I'm having difficultly trying to figure out how to do this.
The effect I'm going for would be like in fighters like SF or DBFZ.
cinemachine target group
I see, I'll play around with this, thanks!
I messed around with it but this seems to place the camera directly inbetween P1 and P2, i tried adding a third object to pull it back which works but then it's not centered between them
hey im looking at adding some automated testing to my game. Do people have good experiences with the unity test framework or are there 3rd party frameworks youd reccomedn instead?
How do i make it so that it only destroys game objects with a certain tag
Oh, I did answer you btw
The part about going into a code channel was for next time
i know
Then what question do you have?
im just kinda new to unity so idont know how to implament a compare tag
The docs include example code
It is as simple as putting it in an if statement and plug in the tag
ok
Here are the docs
https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
thx
i followed it but it still isnt working, is there anything i missed or still need to add?
nvm, fixed it mb\
Was the issue that the collider did not get changed to isTrigger?
I notice you changed to OnTriggerEnter
You CAN keep it in OnCollisionEnter if you wanted
collision.gameObject.CompareTag()
I made a little class for that yesterday
{
public float TimeToLive = 5f;
private void Start()
{
Destroy(gameObject, TimeToLive);
}
}```
I don't know if this is allowed, but I don't exactly know if it's a code question or a UI one, so then i paste it here, hopefully anyone could help me: #🧰┃ui-toolkit message
In the latest version, navmesh workflow has changed a bit. It is now a package as well. Have a look at the package documentation to learn how to use it.
custom editor #↕️┃editor-extensions
hey, in 22.3.40f1 we have this stackoverflow when opening a particular scene, does that sound familiar to anyone?
hey, can someone tell me whats the difference between using a singleton like this: Singleton<ClassName> and making and instance like this: public static Instance ClassName?
Can't tell for sure without seeing the code for the Singleton class but presumably it's a generic way to make singletons without having to implement the mechanics separately every time
The difference is that in the 1st variant, the class has to be derived from the generic class, whilst the 2nd one requires the same implementation inside of every class, and is much less readable
Hey everyone!
I want to create a script that shows/hides a SerializedField in the inspector when certain conditions are met.
For example:
if ("gameObject" the script is attached to has a material that uses a Normal Map)
{
Display the SerializedField variable to be modified in the inspector;
}
else
{
Hide it;
}
Has anyone tried to replicate this similar idea to mine - or am I asking for something impossible?
(asking for a friend)
write a custom editor script. #↕️┃editor-extensions
Trying to get Client.Embed code to run in order to embed a Unity Package I have. The package itself has compilation errors and publishing the updates to verdaccio is not available atm (colleague who has access to do this will be returning in a few days). I wanted to embed and update this locally but due to the compilation errors, Unity doesn't seem to want to play along and let me get the embed code to show up:
[MenuItem("REDACTED/Advanced/Embed REDACTED Package/REDACTED.Backend/REDACTED.REDACTED")]
static void EmbedPackageMenuItem()
{
const string PACKAGE_NAME = "com.REDACTED.REDACTED.backend.REDACTED.REDACTED";
REDACTEDUnityPackageEmbedUtil.SetPackageAsEmbedded(PACKAGE_NAME);
}
The above otherwise works fine (when Unity doesn't have compilation errors)
for future reference, this was caused by a material variant which had another variant as a parent, who in turn had an invalid GUID as parent reference
Hey guys, I have an error where my player can't jump when it's going up, like this
I tried scaling up the ground distance
but well this will happen
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 10f;
public float gravity = -9.81f;
public float jumpHeight = 5f;
public Transform groundCheck;
public float groundDistance = 5f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
Debug.Log(isGrounded);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
Vector3 move = transform.forward * x * speed;
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move((velocity + move) * Time.deltaTime);
}
}
here's the code
is this a pointers moment
i'd like to have a function that can determine which variable to edit
if this is ludicrously hard to set up, ill just do it the messy way with an individual if check
you've just messed up the syntax
int x = method() + 1;
well does this give me the value of the given variable dependent on the conditions, or edit the given variable dependent on the factors
that code does nothing with factors
im hoping to write a function that will keep me from if checking for every specific variable here
trying to condense four if checks into one
is there like a way I can combine ref and return?
like i'd love if I could return a reference to a variable
Why not use property?
figured it out
that was
quite easy actually
I feel silly for coming here, sorry for bothering
sheer dopamine rush of writing code with a new skill
and it works perfectly
thanks for helping me rubberduck this lol
i have this game where you let enemies slide by titling the platform, any advice on how to make it more controlable when tilting in reverse
modify your physics materials, you probably want to constrain the rotations on the capsules as well
and please dont post videos from a phone
AllAnoms.RemoveAll(item => item.IsActive);
i'm not very experienced with linq, this should remove all items that have IsActive set to true correct?
why is that?
because it is against server rules and they are very difficult to see clearly
I would post the "professionals have standards" gif but dyno would eat it 😔
yes, but please dont conflate code one liners with being good, efficient code
well I presume its going to be at least somewhat more efficient than just doing a foreach loop
absolutely not
really????
huh
well I presume this isn't going to eat 2 billion frames (especially because its only called like once a minute) but out of curiosity, how would I do this faster?

