#archived-code-general
1 messages · Page 224 of 1
he’s seeing problems in build vs development build, so that was my first thought
Actually surprised it's not a compile error in the release version
although maybe it gets done at the bytecode level
i forget what the issue was tbh
so those are techincally separate "lines"
The out variable gets initialized before the line at compiler level
point being, you do not want to actually modify/initialize variables within any Debug. calls
Are only Debug.Assert lines stripped? Do Debug.Logs get stripped as well?
in my case, i think my variable was declared before. and I got a NRE because the Assert was assigning it
Debug. everything
this should make your code run a lot better in final built. because you SHOULD be spamming Debug.Assert
Wait I'm confused now, how is anything logged to the Player.log in release build then?
I probably average 0.5 Debug.Assert per method I write
for that you need to write to Console
I actually wasn't sure if it completely stripped everything inside the method call
it does
You'll get something along the lines of
Collider2D col;
if (col.forceSendLayers == 0) {
I have an idea to make a polygon Composite collider2D with radius. I think I might be able to make a class that derives from CustomCollider2D, and add the shapes of a Polygon mode Composite collider, swap to outline mode. Generate, and then add the shape.
After compilation, which is why it throws, that variable is not initialized
oh, that's interesting -- i hadn't considered how getting rid of the part that declares the variable would work out
The inline out declaration is syntax sugar and compiles to a declaration before the call
Hence why you're able to do something like this
if (!thing.TryGetComponent(out T val))
return;
// can still use 'val' here
ah, makes sense
i figured it was something like that
(this is very nice pattern for early-exiting)
Debug.Log and Debug.LogError is definitely logging to the Player.log in a release build. I just tested it.
you could just log a stack trace manually
that's convenient
I've used the StackTrace class in the past
Thanks may have to try that
Yeah so Debug.Assert gets stripped but not Debug.Log and Debug.LogError, so it isn't the entirety of Debug. that gets stripped.
Yep your logs will still get written to some file at runtime. This can be a slow operation (I/O is always slow compared to pure code executing on the CPU), so it's better to strip them out before building a release
your users will also get mad if you write 23 GB of logs
Opens logs:
"here 1"
"here 42069"
"fuck me why this won't work"
"this should be unreachable"
Almost forgot the usual "aaaaaa" and "fgfgfdfdfsrg"
I'm going to start putting jokes in these log files
Initializing dependency injection engine, registered 3 containers
Just kidding we have a tightly coupled code base here
just kidding, we actually shipped a game
Hello guys, I'm having the following problem: I am trying to add a class to a 2d array, I think the adding void is fine, it's just that the class is always null for some reason
[System.Serializable]
public class gridObj : NetworkBehaviour
{
//To change material
public FishNet.Object.NetworkObject soldierMeshRenderer;
//To move the soldier
public Transform soldierTrans;
//The speed the soldier is walking with
//Has to do with the grid, so we can avoid storing all soldiers in an array
//Instead we are going to use a linked list where all soldiers in the cell
//Are linked to each other
public gridObj previousSoldier;
public gridObj nextSoldier;
//The enemy doesnt need any outside information
public virtual void Move()
{ }
//The friendly has to move which soldier is the closest
public virtual void Move(gridObj stuff,Vector3 oldpos, Vector3 newpos)
{ }
}
public override void OnStartNetwork()
{
if (NetworkManager.transform.GetChild(1).TryGetComponent(out GridPartitioning component))
{
gridObj self = new gridObj();// { soldierTrans = transform, soldierMeshRenderer = NetworkObject };
self.soldierTrans = transform;
self.soldierMeshRenderer = NetworkObject;
oject = self;
if(self == null)
{
Debug.Log("self is null");
}
component.grid.Add(self);
}
base.OnStartNetwork();
}
It is done in a multiplayer game, but Idon't think that has any relevancey, sincein the OnStartNetwork is says that it's null
any ideas?
Probably can't use new on a NetworkBehaviour, like you can't do it on a MonoBehaviour
You may need to instantiate an object and add the GridObj component to it
yeah
Also names of types (classes, structs, enums, etc.) start with an uppercase letter: GridObj, please follow the naming conventions
does that really matter?
For anyone that will read your code, yes
It makes it much harder to read when you don't follow the conventions
It also just looks very amateurish
The naming convention is well made, enough for someone to see what kind an identifier is without looking at its declaration
"Anyone" includes yourself, by the way
you'll be spending a lot of time reading your own code
I'm trying to figure out the best way to make a Collider2D that is a CustomCollider2D, based on a CompositeCollider2D. The idea is CompositeCollider2D is set to Polygon mode => put shapes into customcollider => set to Outline mode => generate => put shapes into customcollider.
The issue is that CustomCollider2D is a sealed class, and none of the Cast etc methods of Collider2D are virtual
this is not how you share code here
how to share?
!code
There is also no question here
📃 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.
just writing
Try doing it all in one message, you can hit Shift+Enter to add a new line without sending the message
https://paste.ofcode.org/5W5tQW73vJeFhcBuZ5nE4R
i'm using googlecardboardVR tools and I want to make player move voluntarily. For that I tagged 2 objects with walk and sprint resp. I want that when i point the rectile towards them , i move otherwise don't. In this script, its casting a ray in the game environment, if it colides with the tagged objects, it moves.
As there are no triggers in cardboard vr, so i thought this would work. but not working!
anyone knows?
Hi! I want to make so when this is called, the array called cars have all gameobjects with those tags, any suggestions? Thanks!
I know the + doesn't work for the arrays, I just didn't know how to do it
first you might wanna configure your IDE doesn't look configured
my what?
integrated development environment (IDE)
the IEnumerator?
oh
I understand now
I have it configured, I just took the screenshot before it started properly
gotcha
put them in an array
loop thru the array
foreach (car in cars){
if(car.CompareTag("One") ){
}
not sure why multiple tags are needed here
I have different gameobject that spawn when I hit play, and I want to access them through an array, I just didn't know how to do it I did it this way
Is that.. trying to add arrays togehger with +? That's a first
In the new C# version (out a few days ago) you would be able to do that with a spread operator, but this is Unity
one object can't have multiple tags
what you should do is ditch tags and use types
so one object can have multiple attributes in form of Interface
I want different objects with different tags eachother
kindly help 🛐
huh?
you want to put multiple objects with diff tags in a list or
In another codes, I spawn various gameobjects in the scene, some have the tag Damagable, some have the tag cars, and others have the tag Ground. I want every gameobject in scene with some of this tags in the array
if the do a common thing why not have a common component
they do very different things
Doesn't mean you can't put a script on it that's only for searching objects
This is composition
Those are gameobjects that if they are too far away from the player, despawn them for game optimizing
thats true
ohhh Iunderstand
I liked that code you made
Okay, you're basically just redoing LOD right here
That already exists
Or, just decreasing the camera's far plane
I just didn't know what was it and how to make it, so I just made it myself
What would that do?
Limit how far the camera can render
yeah, but instead of decreasing the detail, I want the gameobjects to deactivate
I just tested that, but it doesn't improve the optimization
It still runs at low fps
have you profiled it
Is the object amount really the cause of bad performance, have you profiled it?
you might need to also do occlusion culling
yes it is
I dont know whats that
use this as well
https://docs.unity3d.com/Manual/OcclusionCulling.html
this only renders what your camera fov can see
I think that's what I'm trying to do, just not sure abt the name
if you look away (have no camera rendering the objects) is the fps still low
If that second message was for me, then your two statements conflict
oh yes, sorry
yes
then what?
ill check that
You cannot know whether X is the cause of performance drops without running the profiler basically
"It's the cause of low fps" - "source?" - "trust me bro"
id double check the profile and make sure you've not doing something like raycasting 1k times an update ;)
I tried deactivating myself the gameobjects, and when I do that, the fps go normal
it could be scripts too tho
They might have scripts on them that impact performance
thats why you profile
Like, doing FindGameObjectsWithTag() 60 times a second is very much not recommended
fr
Now imagine that on 500 objects lol
How do I do that
the script I showed you only called once, when the game started, and only in one object
its very easy and poweerful tool
so your game never spawns new objects?
only at the start of the game, then it stops spawning the ones I'm trying to deactivate
Does anybody know how to make a ball movement system for VR so whenever you kick it it actually acts like a ball?
Ask in #🥽┃virtual-reality
thx
np
I'll try profiling in a few minutes, Unity is rendering the occlusion culling that you showed me
this one time saved me from 5000 batches to meerly 200
also keeping things that dont move checked with static on gameobject improves how meshes get rendered
It just adds a little fps buff, but it's still almost unplayable
I don't understand this, what is causing low fps?
looks like your physics is high, also you need to put in hirerchy mode to understand it better
rendering is also pretty high
you should def go through a basic video how to read Profiler accurately
is there a way to get around CustomCollider2D being a sealed class?
yeah I agree
Learn how to use Unity’s powerful optimization tools for diagnosing and troubleshooting performance problems via a demo on a simple maze game. You’ll be able to use these practical tips and techniques to improve performance in your own Unity projects.
Speaker:
Andrew Jevsevar, Unity Certified Instructor
Did you find this video useful? Room for...
thx!
my idea is to make a “Collider2D” class with its own shape and its own methods to modify the shapes, then use the shapes in a CustomCollider2D to make it work with physics
I'll update you later
would it be possible to just copy all the source code from CustomCollider2D into an identical wrapper class that isn’t sealed?
idk how injected code works in that regard
uhh... UnityEngine.Bindings.NativeHeader is inaccessible due to protection level.
your mind is in the right place for sure, with snippets like these. don't be discouraged!
is there any way to get access to UnityEngine.Bindings? It seems to be necessary to bind methods to the proprietary C++ code
this is all because I'm trying to unseal the CustomCollider2D class
Thanks!
@rigid island How bad is this?
pretty rough lol
you're dipping below 15fps
you have tons of batches goin on
There's also two large allocation spikes
Physics is the thing it's consuming the most
Switch to hierachy mode instead of Timeline to get a list of what uses the most resources
would anyone know how to get around a sealed modifier in a built-in class?
I think thats a lot of trigger stays
Seems like you have some stuff that monitor trigger stays yes
I think I know whats making that
Do you have a lot of script instances with OnTriggerStay() implemented?
Is there a way to see where are the triggerstays that are consuming the most?
I have some
You'll have to enable Deep Profiling (button at the top of the profiler window) to see where in the code the issue is
thanks again for the attention
Profile again, and you'll be able to open the profiler's hierarchy items deeper this time
I don't see any changes
a lot of things
if its enabled keep expanding arrows it should be able to narrow a specific method
so hi could someone help me out i tried to putting gliding into my game by making my velocity change my gravity but now i cant even get off the ground by jumping
You need to run a new profiling session, ie. you need to play the game again
still ends on those two lines
ohhh
thats it
that really fits on what I thought
the problem is that I call those methods, or that I do a lot of thingds in those?
Allocations (CG Alloc) are separated in the Hierarchy, but they are coming from the scripts at the same level
its not those two methods, its the one under them
the props.Ontriggerstay
Its what its the most consuming I think
correct me if I'm wrong
You create a lot of stuff, which means the GC (Garbage Collector) has to work harder in finding and reserving RAM to store the things you create, as well as disposing of objects you don't use anymore to clear up RAM
You'll have to post the code, so we can see what's the source of all these allocations
How can I know if an object is inside this infinitely wide (but not infinitely long) plane?
I would like to know the point in the plane where a vertical line fall thought it
Post the code anyway, I want to see where the performance bottleneck is
What do you mean by that last sentence? What vertical line are you hoping to achieve and what is this for in terms of your game?
And the Instantiate
yeah constantly Destroying too
And a small bit for the lack of CompareTag
someone needs to learn pooling 😏
yeah this whole method screams optimizations needed
no wonder profiler is crying
Yeah especially if this is on a lot of objects. The text objects can indeed be pooled yup
pooling is an optimization you plan for early, but you do later.
it makes sense that now is the time to upgrade
Putting that in OnTriggerEnter should shave off a great part of the slowdowns
if i put my jump in fixed update it doesnt jump immediatly
but if i put in update it does but people said its bad for optimizing
because you check for button presses in update, not fixedupdate. So by the time FixedUpdate comes along, several Update frames already passed
the optimal way to do it is to use InputSystem to call methods specifically when the jump button is pressed
I have a rectangle of infinite width (ignore the vertical yellow lines) and finite length which is defined by two points plus a normal.
If have a green point above the rectangle, I want to get its corresponding (purple) point in the rectangle.
And if the green point doesn't have a corresponding rectangle point, I don't want anything (this is not an infinite plane, but an infinite rectangle).
inputs go in Update
moving rigidbody shouldin FixedUpdate (.velocity / AddForce when accelerate mode)
if you are using Impulse force, Update is acceptable for a frame pressed
if you use Input, that has to go into Update
InputSystem doesn't need to go into update nor fixedupdate
but in no case can you be putting it in fixedUpdate
Plane.Raycast to the rescue! This can roughly do what you want, except the plane extends infinitely in both directions. You'll have to check whether the point you hit on the plane is deemed as "in bounds"
This is a full code solution which does not require the creation of objects in the scene
i though anything physics related had to go into fixed update
Ok
What is this for in terms of your game? This seems like a very niche problem that doesnt need to exist in the first place. If you cant define a max size and use a collider to solve some of the work, you'll need to keep track of every object that can potentially be above this. Then im pretty sure it should be as simple as checking if the current position lines up with the rectangles normal + some offset. That offset is just the finite dimensions of the rectangle
I have a flying object which is moving thought a custom nav mesh link I made and I must handle its height during the movement of the link
Ok, I think I'm narrowing down on my options, and I need a bit of help: I want to make a wrapper class for CustomCollider2D, but idk how to do this since it is sealed. Most of my code uses Collider2D to call Cast, Distance, logic in dictionaries etc. And idk how to add this while keeping compatibility. The class I want to make should be identical to a CustomCollider2D, but it has some extra methods/fields. Any ideas?
Does any1 know what could be causing a consistent an immediate crash when generating lightmaps? This randomly started happening today, many different versions and newly created projects are affected.
Actually I forgot about plane.raycast, as spr2 suggested. thatll be more helpful if you're able to use it
I'm thinking about making a Class containing a CustomCollider2D, make a static dictionary to connect class to customcollider2D, and whenever I want to call on anything with a Customcollider2D, I need to go check this dictionary. Sound like a plan?
you mean runtime or code?
In the editor
Like everything else works fine but I just cannot bake anymore
id try asking #archived-lighting
this is a code channel
is there a way to get a message when an object is destroyed? or when a destructor is called?
I'm pretty sure it is just:
void OnDestroy() { }
just invoke an event inside OnDestroy ?
let's say my target is a Collider2D
I want to know if/when this collider2D is destroyed
and I want to call Foo() when it destroyed. How do I do that
might be easier to look in editor scripts, if you need it runtime maybe there is a better way and might be XY problem
!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.
This should give an idea of what I'm trying to do
I am trying to make a generic wrapper class to deal with Unity's fetish for sealed classes
The way it works is: The wrapper can tell you the thing it wraps. When you initialize the wrapper, it needs to basically add itself to the static wrapper dictionary that ties the wrapper class to the type of component it wraps.
Then the wrapper class can hold whatever things you need
And if you have an object of the wrapped type, this dictionary lets you access the extra information
The problem is: in order to make a static dictionary, I need to know when the component is destroyed to remove it from the dictionary
any idea on how to do this lightly? I don't want to make something that just checks the dictionary for destroyed entries every frame, just to block memory leaks
it would also work if I could subscribe a method to an object being disabled
what's the purpose of this wrapper? Your design seems to be screaming that whatever it's supposed to do, it would best be done as a component as well that's adjacent to this wrapped thing on a GO, not an association in a static dictionary
I can't modify Unity's built-in components outside of extension methods
extension fields aren't a thing
I would love to derrive from CustomCollider2D, making a class that just matches the outside behaviour (so you can call Cast, Overlap, Distance....)
to make a CustomCollider shape that is more specific, and thus has certain parameters/fields for that shape
and this is a general issue: I wish I could just... add fields to built-in components. But I can't
I wish I could inherit from built-in components, but I can't
I wish I could copy the code and make a new class from scratch, but because of how Unity injects C++ code, I can't
I wish I could just change the source code. Change one or two words. but I can't
well you're working against the system here. Make a CustomCollider2D class with a serialized field to a target Collider2D and implement all the same methods. I don't see how your wrapper is going to be a better solution over that, especially since it really doesn't have any functionality
CustomCollider2D is sealed
MyCustomCollider2D that accepts a target CustomCollider2D then
and most methods are injected, with attributes with a protection level that blocks you from copying them
ok, Cast/Distance/Overlapping etc isn't virtual
if 99% of my methods solely depend on a Collider2D, I can't just .Cast it
your wrapper has the same limitation, while also being more complicated and confusing to use though
what is your suggestion
MyCustomCollider2D can't inherit from CustomCollider2D, and inheritting from Collider2D just gives the wrong behaviour.
and I can't give Collider2D an interface
I just described it. I still don't know what your ultimate objective is though. Maybe your specialized Cast/Overlay behaviour should be in a static class instead and you avoid wrapping anything
I don't have specialized Cast/Overlap/Distance behaviour
is this your suggestion?
what does MyCustomCollider2D inherit from, if anything
it beats the stuffing out of a static dictionary, so yeah. But what do you want to do with CustomCollider2D? This looks super generic already
MonoBehaviour
This would basically give me the ability to know when the object is destroyed.
yes
how is this different from the wrapper method?
my whole game depends on Collider2D, and Collider2D methods
did you find a way to solve the object destruction problem? Because the next point on that train is "well I'll add a component to the wrapped component's GO..." and then all your previous code might as well deleted, and you'll end up at my suggestion
I think I will give my wrapper an initialize method that takes in an Action, that gets triggered on destruction
and a different monobehaviour that it lives on can tie it
the wrapper would make it so I only need to call the wrapper for a couple of methods that need really specific behaviour
I think this is what we're going with
Generic class. If you inherit from this, then you can maintain it automatically
the idea is to compose this wrapper into another monobehaviour
or just... let it be in the ether, not composed into anything
is there a built in function to query if Bounds is visible for a specific camera
since they do those checks with meshes
wondered if they exposed the function for us to query freely
i really would like to avoid doing the math myself given they have the function already there some where for their OnBecomeVisible etc
https://docs.unity3d.com/ScriptReference/GeometryUtility.TestPlanesAABB.html
is this what u want?
it looks like it might just be
thank you @lean sail
shame they didnt just have a helper function on the camera itself
like _camera.IsVisible(myBounds)
https://hatebin.com/mtuqmpkhld
im having trouble trying to get my player to reset horizontal momentum when running into the side of a platform
how can I prevent the "bed" from detecting the mouse over once there's a UI above it?
ui has an option to block raycasts
some where in their inspector
i think you need to set the body's forces on x to 0 aswell
the thing is, I'm not using raycast to hover on an object. I use "OnMouseOver"
yeh i know OnMouseOver is doing a ray check on your behalf
if you block the rays it shouldn't trigger
on your canvas gameobject add canvas group component
and tick block raycasts
sorry if im being dum but how do i set the force
oh you might have to do body.AddForce() and give it equal and opposite force on x axis
to cancel it out
body.totalForce = new(0,body.totalForce.y);
might also work
did it and it still detects the mouse
well you should really use IPointerClickHandler interface rather than OnMouseOver
i believe that will respect the ui
I see.. alright thanks :D
im getting an error saying TotalForce isnt defined
i might just be being dumb
oh my bad
doesnt appear to be working
sorry my internet did a funny there
honestly i dont have any clue why its not working
all i know is that if i put a Debug.Log before the set velocity it runs the log script
If normal.x != 0, you set velocity.x to 0
!= mean is not right
Not equal, yes
ye what i mean lol
yes
Ok, well that is why the x velocity is reset when you hit the side of a platform. You do it explicitly.
i want it to be where when you stop touching the side you dont keep your velocity
from before you hit it
like in mario how if you run into a block and in the same jump you stop touching the block from gaining height you dont keep momentum @spring creek
Well you set x velocity every frame in update (that should be in FixedUpdate, but that is not the issue). You should make a "canMove" bool or something and check that before moving. If you hit a wall then make it so you can't move until you hit the ground (if I understand what you want)
no thats not what im asking
you know how in mario you need to build momentum to go fast
but if you run into a block or something you lose all your momentum
thats what im goin for
You don't have anything to do with momentum in code. You set fulls speed or set 0 speed.
And no, I don't know anything about how it is in mario, sorry
how do I make it so that any interaction like dragging with the mouse, scrolling to zoom and interacting in the background is disabled when a UI appears?
Which input system are you using?
wdym by that?..
There is the new input system and the older input manager.
Are you writing things like Input.GetAxis, or using callbacks?
If you aren't sure, you are 99% using the old input
I do use the Input.GetAxis for my zoom
this sounds like a really dumb question, but how do i add non-ui text
Ok, well you'll want to just have some condition wrapping the input. Like when menuOpen is false read that input, when it is open, you don't
You could also have it in a script that you enable or disable (disabling a script only disables unity methods like update btw)
wait, how do you disable a script?
this.enabled = false; or
scriptReference.enabled = false;
I kinda wanted it to act like a pause(?). Here when the question appears, any interaction outside of the UI will be disabled. I want it to have that interaction...
I see.. alright I'll try that
Combine what I said with Time.timeScale = 0, which will catch most things. But might not do it all
It's up to how your game works
Do you mean 3D text in your game environment? If so, under the "GameObject" tab, there is "3D" along with your common ones like cube, sphere etc, there is also "3D Text" - Unity has a legacy one, and there is also TextMeshPro, which is the recommended
no im making a 2d game
You can use that in 2d
oh
2d in Unity is still 3d
TMP is cool haha. Worldspace text is great.
hello me again
the cameraDrag and cameraZoom did stopped working when disabled. but the bedFunction still does the "OnMouseOver" dispite it's script is already disabled. why is it like that?
how would i make a loop that moves something up and then moves it down and then repeats
Yeaaahh, that wouldn't get disabled. Only Update (and Fixed/LateUpdate, and I think OnTrigger/OnCollision do).
Could the menu simply BLOCK everything? Not sure if that would work.
Otherwise gotta make a bool.
I'm trying to do that but couldn't find a way. I'm now trying if I could disable the collider instead to prevent it with any interactions
this worked XD lmaooo
@spring creek sorry for the ping but thank you so much for introducing me this .enabled really helped a lot!
Sounds like you might be looking for a PingPong: https://docs.unity3d.com/ScriptReference/Mathf.PingPong.html
Since this return a float you can manipulate one axis at a time with it, heres an example that seems similar to what you want to achieve, searching "unity c# mathf.pingpong vector": https://forum.unity.com/threads/ping-pong-gameobject-up-and-down-from-current-postion.226442/#post-1509140
why wouldn't you just read the documentation that you were linked?
i got confused
i was lookin at this page too https://stackoverflow.com/questions/61306895/what-does-unitys-mathf-pingpong-actually-do
PingPong returns a value that will increment and decrement between the value 0 and length. confused you?
i know what it does
im trying to apply it
to move something
im a bit slow
i just want to move something up and then down and then repeat and im tryin to figure it out rn
i think im gettin it now though
@elder chasm You want to do this without physics? Just forcibly set the location every FixedUpdate()?
yeah i think ive got it almost figured out gimme 1 sec
Rather than reinventing the wheel, use a tween library like this https://dotween.demigiant.com/
DOTween is the evolution of HOTween, a Unity Tween Engine
Think of it as a library to blend between two values over time, but incredibly flexible and customizable
oh thanks
It can feel a bit overwhelming bc it can do a lot, but its good to have a basic understanding of it. dm me if you ever need help with it
DOTween.To(() => _canvasGroup.alpha, x => _canvasGroup.alpha = 1f, 0f, UIFadeInOnActiveGlobalConfiguration.Duration);
i may be stupid but what am I doing wrong here to make this canvasGroup's alpha go from 1 to 0?
dont mind the incredibly long name for that class
speak of the devil
think about what your setter is supposed to be doing, and what it's actually doing
I'm not sure I really understand the syntax of this command 😕
DOTween.To(() => _canvasGroup.alpha, x => _canvasGroup.alpha = x, 1f,
UIFadeInOnActiveGlobalConfiguration.Duration);
``` im trying to figure out why this works and the other thing doesnt (i tried with "x, 0f" too)
that has a correct setter
DOTween.To(getter: () => _canvasGroup.alpha, setter: x => _canvasGroup.alpha = x, endValue: 0f, duration: UIFadeInOnActiveGlobalConfiguration.Duration);
with labels
that one is now correct
what 
your first snippet ignores the value of x and sets alpha to 1 every time
DOTween has builtins for fading, i think it's _canvasGroup.DOFade(...)
you meant to do _canvasGroup.alpha = x
i see you figured this out
ah well its still not working with this but im going to try DOFade
that code is correct. your canvas group (your hierarchy) is probably not set up correctly
or, rarely, you may have configured dotween to not autoplay
or you set timeScale to 0, that surprises people every now and then too
no whats weird is that it sets the alpha of the canvasgroup to 0 immediately
well
then the duration is zero. or, you are setting it to zero immediately elsewhere
oops
well at least i wasnt wrong about being stupid
it's okay
Having a issue when the player is wall jumping it will sometimes go down rather than up, really confusing because all the values are positive, I can't figure it out for the life of me.
https://paste.ofcode.org/9ZgxhPnDCMsFZU5SYBGy52
What kinda collider(s) does your player have?
Asking about the collider, not the wall check object
Anyway you could start by visualizing the forces, collisions etc. with Debug.DrawLine and such
Hello, why isn't value assigned to the StartCoroutine(coroutine)?
It also throws the IDE0059 on the value =
/// <summary>
/// Stops the value coroutine if it isn't null and assigns it to the newly started one
/// </summary>
public void AssignCoroutine(IEnumerator coroutine, Coroutine value)
{
TryStopCoroutine(value);
value = StartCoroutine(coroutine);
}
the Coroutine is the class and it should save the reference, shouldn't it?
do I just make value a ref ?
oh, just remember you cannot assign a class to the smth, you can just change its fields
that's a stupid mistake 🙄
yes, got it now, thanks 😁
Ah sorry for my misunderstanding, im using a box collider
I would use a bool instead of relying on float comparison and transform.localScale.x
Or at least check the sign of it instead of exact value
Not sure how to fix your walljump issue though
Am i correct in saying having a public bool method will be originally assumed as false?
EG:
{
return (Time.time - lastEnteredTime) >= CooldownTime;
}
No
It'll evaluate what's after the return and return that value
Methods do not have default values, you'll only know the value when you call (execute) it
I see
So in this case it will check if the elapsed time is greater than or equal to the cooldown time and then the method would return true
So am I understanding that boolean methods technically dont have a base true or false state
They just turn true once a returned condition is met?
No method has a "base state", only variables do
Got it, thanks
it just returns the result of expression
I followed this video https://youtu.be/eL_zHQEju8s?si=uLLHWhr-6kZgfZaV on water physics and at the end of the video he says how to add movement but doesn't show it can someone help me do that.
In this tutorial you'll learn how to set up boat movement and dynamic water physics in Unity.
Check out my devlogs: https://www.youtube.com/playlist?list=PLXkn83W0QkfmQI9lUzi--TxJaOFYIN7Q4
⎯⎯⎯⎯⎯⎯
Catlike Coding's article about shader-based vertex manipulation and Gerstner waves: https://catlikecoding.com/unity/tutorials/flow/waves/
Discord s...
public class Floater : MonoBehaviour
{
public Rigidbody rigidBody;
public float depthBeforeSubmerged = 1f;
public float displacementAmount = 3f;
public int floaterCount = 1;
public float waterDrag = 0.99f;
public float waterAngularDrag = 0.5f;
private void FixedUpdate()
{
rigidBody.AddForceAtPosition(Physics.gravity/ floaterCount, transform.position, ForceMode.Acceleration);
float waveHeight = WaveManager.instance.GetWaveHeight(transform.position.x);
if(transform.position.y < waveHeight)
{
float displacementMultiplier = Mathf.Clamp01((waveHeight - transform.position.y) / depthBeforeSubmerged)* displacementAmount;
rigidBody.AddForceAtPosition(new Vector3(0f,Mathf.Abs(Physics.gravity.y)* displacementMultiplier, 0f),transform.position, ForceMode.Acceleration);
rigidBody.AddForce(displacementMultiplier * -rigidBody.velocity * waterDrag * Time.fixedDeltaTime, ForceMode.VelocityChange);
rigidBody.AddTorque(displacementMultiplier * -rigidBody.angularVelocity * waterAngularDrag * Time.fixedDeltaTime, ForceMode.VelocityChange);
}
if (Input.GetKeyDown(KeyCode.W))
{
}
}
}```
it says just apply force in forward direction. you should learn how to do that
so just look into AddForce and AddTorque for rotation?
Hello, what's the best way to set the mouse position in Unity?
I've found some stuff that uses System.Windows.Forms, but it's not the best thing to use in Unity, or am I misunderstanding something?
Maybe consider making a game mouse cursor and hiding the OS cursor.
mouse position is controlled by OS (and read from the hardware)
there should be some system calls to change the mouse position in the OS, maybe google it by yourself
Yes, I do have this logic already. I'm drawing the GUI cursor. But I am talking about the real OS cursor's position.
I cannot change OS cursor's position by just changing the GUI
You'll need to make OS specific calls to manipulate the OS cursor.
Which would differ per platform etc
you dont need GUI for it, its part of the Cursor api
Else consider manipulating the non OS mouse and acquiring deltas from the OS mouse instead.
I know it. You cannot change the Texture's size with the built-in Cursor
you can i think with CursorMode.ForceSoftware
so I had to implement my custom logic
but I draw custom custors that're scriptable objects that have their fields like width, height, rot angle etc.
I surely cannot achieve this stuff using the built-in cursor
no you can only set image, you are correct
but you can set larger image than 32 which hw cursor allows with software mode
which ui is drawing the cursor?
uGui?
that's great, 'cause I don't want to rewrite my whole custom cursor logic I've been implementing...
OnGUI()
i strongly advise you not to use GUI calls anywhere in build
they are fine in debug build/editor
Build? It isn't Play / Game mode, right?
reason is simple a single call anywhere in the project will spin up the GUI system in build which with zero load will still consume about 2ms per frame
no, build is build
the .exe
I see, build is editor mode
while in editor you can use GUI if you #if UNITY_EDITOR #endif
I don't use it in editor though, so no troubles 🙄
yes you are planning to use it for the game itself, so it will go into the build
and your performance will suffer
oh, so the Build Mode is when the game is played outside of the Unity?
build is the process of creating the final executable, asset bundles so that the game is playable outside the editor, yes
term build refers to the .exe and all the files of the published game
Hello. Running into a weird issue/bug(?) when manually playing animations onto a standard Animator component.
The thing I am trying to do is
- create an object
- specify the animation to play on it by name
The behavior I am seeing is that for 1 frame after creation, the object is drawn with a sprite from the default (from entry) animation state instead.
Relevant code snippet, I removed some irrelevant lines and simplified the code. I think it's more likely to be me misunderstanding some nuance of the unity animation system than an actual programming error;
var new_obj = GameObject.Instantiatekind, position, rotation);
var animation_comp = new_obj.GetComponent<Animator>();
animation_comp.Play(animation_name);
I feel like this didn't used to happen, but I cannot say that for sure.
seems the transition between states takes time
How would I specify this, though? I suspected that was it but the states do not have an actual transition within the animator
*animation controller
Drawing a custom cursor in OnGUI method
first look through the api and try finding some way to force transition instantly https://docs.unity3d.com/ScriptReference/Animator.Play.html
it seems the normalized time has potential to fix your issue if you provide 1
that seems strange. Reading it it seems that normalizedTime would be used to pick the starting point in an animation consisting of blend+target animation. I'll try it but my guess would've been I'd jump to the end of my animation. Happy to be wrong though
hah. the behavior I am getting is;
- Still 1 frame of default state
- Rest of animation skipped
does it have "play on awake" ?
sorry, I am not familiar with that setting. where would that be located? is it in the animation controller, the animation, or the renderer?
the animator component
frame delay may be the animator no in isInitialized state yet
so your Play command is buffered
the actual animator, at least from inspector, does not expose such a variable. but it has a 'normal' update mode and a 'always animate' culling mode
Interesting, I suppose it's possible for the object to be drawn 1 frame before it's updates methods are called? It seems like a weird thing for unity to do though
Thank you, I'll have a look on that! 😄
I'll try to force the initialization with rebind
youre right, try - switch inspector to debug mode, tick Keep animator state on disable
im shooting blindly i dont remember if i had this issue or not and if i did anything to remedy it
so im scratching off the bottom of the memory barell for potential fixes
this wasnt good enough
yeah it is understandable. I sure sometimes wish I could sidestep the animator system entirely 😬 sadly not an option I think
it is with Animancer
👀 I'll have a google later
alright I managed to follow this. But I still dont know where the 'play on awake' would be found
i probably mixed it up with something else
lots of unity component have setting like that
no worries
that Keep animator state fixes nasty issue when disable/enable of the animator would break its internal state
it has potential to fix your issue, but its low, but still worth a shot
I think it might've if I wasn't creating a new object every time?
There are actually a lot of fun interactions I am noticing now that I am truly stepping through this unity step-by-step
if it fails, my last suggestion is to manually go through transitions in the state machine itself and disable "has exit time" on them
another thing you can try doing
is when you spawn the object, disable/enable it
feels a little silly that that'd be the thing, considering I am not actually using any of the regular transitions
disable it for 1 update frame would certainly work around this
if something pops in mind ill share, atm nothing
I am noticing another problem semi-related to this now, too;
The physics outline consistently lags behind the animation by 1 frame (first frame has some sort of prefab default prism structure)
I cannot seem to copy InputAction.CallbackContext and it's making my input based replay system fck up when it tries to read a vector2 from the context.
How can I copy it anyway and fully?
To illustrate;
frame 1. Gray is the visible effect, Red is the hitbox object drawn. Green is the physics outline of the hitbox.
frame 2. The hitbox object now has the right sprite, but the physics outline is following the incorrect sprite from 1 frame prior
frame 3. Behavior is as expected
is it moving in FixedUpdate?
in any case, that is normal, physics dont step in sync with Update
are you calling Play in fixed update?
I dont think so but let me double check
ah, so because the sprite render physicsoutline is handled by some fixedupdate thing, it might be out of sync with displayed graphics?
all colliders live in a separate physics world which is synchronized with unity scene
the physics world is updated at fixed rate, Update is not
Ok no almost by definition I cannot be. Call stack starts at an event fired by an animation
try calling https://docs.unity3d.com/ScriptReference/Animator.Update.html after Play
great!
I'm confused as to why the commented line gives an ArgumentOutOfRange exception
Debug.Log shows that shapes.GetShapeVertices breaks when i=1, and shapeCount = 2
can it be that shape 2 has 0 verts?
when I look in debug mode, that seems to not be the case
PhysicsShapeGroup2D is kind of weird. I think it stores all the vertices in one big list
then each shape corresponds to a range of indices
ah ha. I can use the assembly browser, but I couldn't see the line numbers
post the stacktrace
ok this doesn't make sense. Stacktrace says to look at line 2654, which is a different method
versions differ
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List1[T].get_Item (System.Int32 index) (at <130809ae6f984869a6663c878f16e3f3>:0) UnityEngine.PhysicsShapeGroup2D.GetShapeVertices (System.Int32 shapeIndex, System.Collections.Generic.List1[T] vertices) (at /Users/bokken/build/output/unity/unity/Modules/Physics2D/ScriptBindings/Physics2D.bindings.cs:2654)
LoupExtensionMethods.LoupPhysicsExtensions.ToStringVertices (UnityEngine.PhysicsShapeGroup2D shapes) (at Assets/Scripts/GenericPhysics/BasicKinematicMovement.cs:452)
CompositeColliderRound2D.MakeRoundedCompositeWithoutWrapper (UnityEngine.CustomCollider2D custCollider, UnityEngine.CompositeCollider2D compCol, UnityEngine.PhysicsShapeGroup2D& shapes) (at Assets/Scripts/GenericPhysics/CompositeColliderRound2D.cs:99)
I had to cut off the stack trace because it is too long
shapeVertices[shapeVertexIndex++] the only indexer in that method
uh... that is different from where the assembly browser brings me
but it looks the same
can you use the debugger and check if groupVertices matches amount of verts in both shapes
anyway, I don't understand why I would get an argument index out of range exception
because of a bug, most likely
can I put a breakpoint in the assembly browser?
no just in your IDE
anyway, the point of all this is to debug more easily, because I see when I add 2 physicsshape groups, the result is different
my shapes has 2 shapes, one with 4 and 5 vertices. Groupvertices is 9 long. which is right
which unity version?
check each shape vertexStartIndex
do any one know how to get desktop's audio
OH shit I found it
Desktop's audio?
my second shape has vertexStartIndex = 5. First shape is 4 vertices long. So the start index should be 4
lets say i am playing some music on spotify so it should detect the music so that i can get the spectrum values and stuff
ty cache. I'll report the bug
does anyone have an idea on how to recreate tf2's movement?
probably fails under specific conditions
i don't think so
when shape is inserted it may report incorrect vert count
or something like that for some specific shape
int num = physicsShapeGroup.vertexCount;
groupShapes.AddRange (physicsShapeGroup.groupShapes);
groupVertices.AddRange (physicsShapeGroup.groupVertices);
if (count > 0) {
for (int i = count; i < m_GroupState.m_Shapes.Count; i++) {
PhysicsShape2D value = m_GroupState.m_Shapes [i];
value.vertexStartIndex += num;
m_GroupState.m_Shapes [i] = value;
}
}```
This function doesn't make sense. This is .Add
groupVertices uses .AddRange to add the new shape to the end of the vertex list
and then it goes through all the old shapes, and shifts their start forward
that's not correct
that's flipped
it's so wrong, that this function was probably not tested
I fixed it by not using.Add
bro. this component was not tested. wtf unity
This part of the code takes about 712ms to excute. chunkList is a arraylist of chunkinfo. Any idea how to make it performe better
I've had something like that before
do you have ruletiles?
and how many tiles are you setting at once?
what is var.Positions.Length ?
also, don't use Time. that's wrong
you want to use stopwatch
DoWhatever();
stopwatch.Stop(); Debug.Log("Time it took to load level (in ticks): " + stopwatch.Elapsed.Ticks);```
stopwatch is designed to actually properly measure this stuff
does that help?
This might be a rather dumb question but is it worth having a helper method to narrow certain calls which use GetComponent?
say:
if (target.GetComponent<Health>())
target.GetComponent<Health>().Damage(data);
and using a static helper to implement this so I can just call something like
HelperClass.DoDamage(target, data);
as if this may be called lots, condensing it like this is nicer and any class can access it. I'd like it to condense my code but wasn't sure if there was a better way than this. I'm presuming I could also use GameObject.SendMessage as an event-ish route but I'm not sure on its performance
I can think of a few ways to do it fine, i'd just like to know which ways would be better practice and why, ta!
what is the type of target
GameObject
if the objects is nondeterministic, eg argument in OnTrigger/Collision callback then i prefer tryGetComponent (it is just two lines of code) otherwise just reference to the script
thats cool but can you invert a binary tree?
what?
invert the tree
so:
if (target.TryGetComponent<Health>(out Health health))
health.Damage(data);
or something like this inside a helper method? meaning it does something if it exists and does nothing if the target has no health
look likes spam
lmao
just curious but what would the rough performance difference be between something like this and GameObject.SendMessage(...) ?
i would do this if you prefer to use helper method
public static bool Method(){
return true if component (ie the script) exists
}
``` then call it as
```cs
if(Helper.Method()){do works}
else other works
since you may have further logic to be performed depends on whether there is the component
ah fair point, I'll probably make it a bool and return true if the default path is used and false if not, this is gonna be very general and used by a lotta stuff as a baseline so it doesn't need to handle special behaviour cases in the helper
I am thinking of using the NotificationCenter code off the Wiki:
http://www.unifycommunity.com/wiki/index.php?title=NotificationCenter
As far as...
ta
I question some of these methods. Why would you ever use this instead of just grabbing the references?
!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.
Talking to me or?
https://gdl.space/udumumawuz.cpp I trying to make boat movement but im having trouble with the turning.
bro, that whole block of text was for you
That was delay I sent that message over a hour ago
sorry was out of internet for a bit let me see what i can implement
this is not working!
i want to move the object in the direction camera is looking when i click the screen
i'm calling this onpointclick from another script (attached to some other object)
What's the best way to make a Narrator System? I was thinking about a SO with audioclip and some other info that you can attach to a Game object script that handles based on different implementations (collisions, interaction, player stuff) etcs handles the events raising to the main Narrator System
you've been here around to know
!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.
i thought its a small code snippet 😅
no, regardless they should at very least go in codeblocks
screenshots are the worse for code
also not accessibility/screen reader friendly
https://paste.ofcode.org/Bknseq9ypEUNTGjbvXFcHn
this is not working!
i want to move the object in the direction camera is looking when i click the screen
i'm calling this onpointclick from another script (attached to some other object)
what is supposed to be calling OnPointerClick()
i show u, just a sec
I'm trying to figure out the smartest way to handle depenetration. Some options:
- One pass through all moving objects, iteratively trying to depenetrate one at a time.
- Many passes through all moving objects, with a single depenetration attempt
- Other?
Any suggestions?
should test
Google.XR.Cardboard.Api.IsTriggerPressed
if its a one frame event the translate won't do anything
Debug.Log inside the if statement should tell you how many times its being called
this player has the movement script which includes onpointer click
and the CardboardReticlePointer has the rectile script which calls the player one
I understand
but its void update 🤔
yes but if pressed , assuming is similiar to GetKeyDown or new input's Pressed, only happens it one frame that won't be enough to keep moving
you would need a bool.
Opinion?
Gets a value indicating whether the Cardboard trigger button is pressed this frame.
its one frame
what to do now
put a isMoving bool in Update and activate on taps, or use the TriggerHeld function to hold button down ?
let me try
if you wanted to only move on each tap then the code is fine but the moveSpeed is too low
like way low esp with Time.deltaTime
no i wanted to move while its presed
@clever trellis you did Vector3 movement = 10f * Time.deltaTime * Camera.main.transform.forward; (0, 0, 1)
say Time.deltaTime was 0.0063257 that frame you would only moved about (0.00, 0.00, 0.06) in a frame
if a put the code directly inside is triggered func, it functions fine ie. moves the object the script is attached to (the rectile dot)
but i want to make the whole player move
ig OnPointClick is not being called
wdym its not being called? what is your current code
i mean i think the rectile script is not able to access the parent player
why would it?
children transforms do not move parents
did already
transform.Translate(movement);
ohhhhhh
transform property is the object script is on
😭
just put Movement on the main Player object
its on main player only
ig its the issue
uhhh you have some compile error I think
your script is named different than your class
should they be same?
yes
Can anyone help with this problem... recently i made my game multidevice so it can be played from pc mobile and ps. However to do this i had to switch to the new input system while all my scripts were coded woth the old one. I found on unity how the controler is but does anyone know how is this line translated: Input.GetAxis("Horizontal"); or at least how to make smooth movement using it?
<i>AndroidPlayer "samsung_SM-M515F"</i> OPENGL NATIVE PLUG-IN ERROR: GL_INVALID_VALUE: Numeric argument out of range
how do you know that from this code alone ?
Player if statement has nothing in it
It depends on what you want out of the new input system, but this goes over the basics to get going https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/manual/HowDoI.html
Getting a missing reference exception for a destroyed delegate even though i am removing the listener on destruction?
Is this happening on scene unload?
no, on player death, i have an event for whenever the player dies, it's supposed to disable all ai in the scene
wait could the fact that it's inheriting from a base class mean something?
I imagine it could, but it shouldn't inherently change how this works
Logging subs, unsubs and whenever that method is called could provide some hints
sorry how do i do that?
Connect the debugger and throw down a breakpoint and usually you can get a stacktrace of subscribers
Using the debugger might help, but knowing when you are subbing and unsubbing from events as the game goes might be more helpful. You can log with Debug.Log
^ if this was the case, objects get destroyed immediately, rather than waiting for the end of the frame (because there is no end of the frame, I guess)
I had trouble with this
but doesnt ondestroy still get called?
Yeah. My problem was that I used a unity property in the process of trying to unsubscribe
and so it threw an error
looks good bro
but doesn't work
is it possible to convert points in worldspace to points on a texture?
like if I get a clicked point can I get where that would be on a texture
or vice-versa
Good day to everyone, I have a giant memory leak
I'm now trying to check if an object has moved to another grid, so I can update it, here is the code:
Vector3 oldPosition;
Vector3 lastPosition;
public void refresh()
{
oldPosition = lastPosition;
lastPosition = transform.position;
addtoPart.move(oldPosition, lastPosition);
}
public void Awake()
{
waterManager = GameObject.FindGameObjectWithTag("WaterManager").GetComponent<GridManager>();
addtoPart = GetComponent<AddToPartitioning>();
InvokeRepeating("refresh", 1,1);
lastPosition = transform.position;
oldPosition = transform.position;
}
this is on the class my object is inheriting from
public void move(Vector3 oldpos, Vector3 newpos)
{
gridObj[] list;
Vector2 pos = partitioning.grid.gridIndexAtPosition(transform.position);
partitioning.grid.returnObjectInCell(new Vector2Int((int)pos.x,(int)pos.y), out list);
foreach (var item in list)
{
if(item.soldierTrans = transform)
{
partitioning.grid.Move(item, oldpos, newpos);
break;
}
}
}
actual function it calls
I do not think that any of these functions would have anything to do with it, since I'm using them elsewhere too, problem free
What happens is that I start the server, loads up and I gain like 2 gb of memory in less than a second and Unity crashes.
Weird thing is that the profiler shows as if everything was fine
that is normal profiler activity, but I couldn't get more data because it crashes
if and break
if its crashing, it definitely isn't normal
profiler says I'm using less than 2gb memory, while it's using up to 5 while crashing itself
censorship in effect or what
anyway I removed the move function from the foreach and now it doesn't
Does this happen if you disable those scripts? Just to be certain something in those scripts are producing gigs of memory usage somehow?
so I guess I gotta look at that
Oh, disregard my last comment then lol, maybe you have multiple instances of that script with large lists on each to loop through, gigs sounds concerning if that's the case though
@spring creek I literally complimented the dudes work, you people are something else
dont ever dm me again
list aren't big and only 1 is running
weird because i'm not seeing any loops in it or anything that would cause memory leak
I'm not getting errors so I really have no clue
ig I can use a rendertexture
I have never dm'd you? Stop being rude to people
You complimented them, yes.
Then got upset they responded by saying it didn't work...
A render texture could work, I believe there is a mathematical way to convert coordinates from one system to another, though I don't remember the formula, maybe you could look into "coordinates conversion"
okay I have reduced the problem to the ADD function
public void Add(gridObj soldier)
{
if (!init)
{
return;
}
if (soldier == null)
{
Debug.Log("tryingto add null");
}
//Determine which grid cell the soldier is in
Vector2 cellPos = gridIndexAtPosition(soldier.soldierTrans.position);
int cellX = (int)cellPos.x;
int cellZ = (int)cellPos.y;
//Add the soldier to the front of the list for the cell it's in
if(cellX > size || cellZ > size)
{
Debug.LogWarning("Object is out of the bounds of the grid partioning system, at position (" + soldier.soldierTrans.position.x + ", " + soldier.soldierTrans.position.y + ")", soldier.soldierTrans);
return;
}
soldier.previousSoldier = null;
gridObj gridj = cells[cellX, cellZ];
//soldier.nextSoldier = ;
//Associate this cell with this soldier
cells[cellX, cellZ] = soldier;
//Debug.Log("Added to " + cellX + ", " + cellZ);
if (gridj != null)
{
soldier.nextSoldier = gridj;
//Set this soldier to be the previous soldier of the next soldier of this soldier (linked lists ftw)
soldier.nextSoldier.previousSoldier = soldier;
}else
{
}
}
```this is it
the only Void that this is calling now is gridIndexAtPostion
but that is literally just math```cs
public Vector2 gridIndexAtPosition(Vector3 position)
{
int cellX = (int)(position.x / cellSize);
int cellY = (int)(position.y / cellSize);
if (cellX < 0)
{
cellX = size/2 + (-cellX);
}
if (cellY < 0)
{
cellY = size/2 + (-cellY);
}
// Debug.Log(position + " is at the pos, cellpos x = " + cellX + ", y = " + cellY);
return new Vector2(cellX, cellY);
}
why does 2022 LTS editor cap my framerate? can I make it not do that
Perhaps you have VSync on in game view?
is there a reason the camera is not seeing the world-space canvas? this is not the main camera, dont know if that matters
nope
oh wait now it isnt capping?
odd
ok but second issue is more important
idk why it cant see it
You sure your camera is not behind the canvas?
yeah in either case it doesnt show
Culling mask on everything?
yup
maybe its a priority thing?
oh I dont even have that setting lol because built in rp
Oh, then I don't know, I know nothing on the build in RP
I have a method called in Start(). How do yield return to try to execute later within the same frame?
You can turn the Start method into a coroutine or call another coroutine from it. However, if you're delaying a single frame, you likely have a bad order of executing your code/references.
You shouldn't need to delay a frame in order to solve something like an NRE
So I need to create a minimap and I have the full minimap working however I need to manually place 2D cube sprites on the boarders of ALL my walls, doors and objects I want to show up on the minimap.. Is there a better way to have the minimap camera just look at all edges of a wall with X tag and render that with a color of my choice ?
for some reason this getkeydown only fires once and never again. i tried using just getkey, but then after pressing the key once, it acts like the key is still down forever. cant find out why.
Where is that code being called?
Update()
i have a similar thing for a different key thats also in Update() and this one works perfectly fine
these are very different
the inputs are working
the thing you are instantiating is interacting with the raycast in a surprising way
rite its just i thought the whole function would only be running at all if the GetKeyDown is appearing true, so if the key wasnt sticking down then it wouldnt do anything
i'm not sure why you are multiplying transformdirection by 10
GetKeyDown will only fire for the frame that the key was detected as being "down", and not continue, GetKey will fire for every frame the key is detected "down" and remains held "down", so if you have a high framerate, GetKey could be called multiple times within the time it takes you to lift your finger off the key, unless you are really fast, you can test this by just logging something like if(Input.GetKey(KeyCode.Space)) {Debug.Log("space hit");}
it means you're not sure what's giong on
there's nothing wrong with your input code
i know
if you write debug.log inside the input.getkeydown rightshift version - notwithstanding an extremely unlikely configuration in your OS - you will see it correctly occur; if you try to replace rightshift with something else, you will still see your bug
focus on the raycast and the fact that you are instantiating something, which itself has a collider
and that you are using a very short distance
yeah i know man i get it but then whats wrong with the raycast
for some reason
it's very blub. there's nothing wrong with the raycast per se, it's the object you are instantiating is messed up somehow
its just a cube with no scripts
i dont know why im chosing that distance man it just works fine normally
im making a really bad minecraft clone
heres how the placing goes weird when its GetKeyDown. it only places one and then never does it ever again
and here's how it goes with GetKey. spawns them forever after pressing the key despite it not being down
nothing
what did you put as the prefab slot that youare instantiating?
its just a cube with no script
okay, but is it from your assets directory, or something in the scene?
lil man down there
also, there must be more going on
because it's being instantiating at a raycast hit
i was honestly confused on why it was spawning on a grid tbh
i didnt make it do that but it did it anyway
i don't have enough context to help i'm sorry.
there are a lot of things that could be wrong
it takes only one checkbox
or one error somewhere you haven't shown us
idk theres no errors coming up at all
the entire update function
apart from the object refs above it this is all the code in the project
What is the easiest way to check how long is remaining in a Coroutine?
@polar marten yeah no its DEFINITELY the Input.GetKeyDown(KeyCode.RightShift()) because using the E key works perfectly fine
Coroutines dont track time, they can just yield functionality, whats the context of what your trying to do?
=> string.Join(", ", list.Select(x => x.ToString()).ToArray());
public static string ToStringUseful<T>(this List<T> list, Func<T, string> entryToString)
=> string.Join(", ", list.Select(x => entryToString(x)).ToArray());```
Is there a way to set a default value for a Func?
Simply I have three seperate booleans that need to be flipped to true at seperate times and I need to display this countdown as a text UI element
So if I use bool1 for example, when it becomes false, I wanted to run a Coroutine for float X seconds
Then during this I wanted to display the countdown
Should I just do a time - time.deltatime
this would be a lot simpler if I could just set a default value for that Func
You could either start a new coroutine for each bool, passing the time that should be waited, or what I often do is use Time.time instead of deltaTime, and check for (or in this case, yield) the difference, for example:
float timePassed;
void SomeFunc()
{
someBool = false;
StartCoroutine(SomeCo(ref someBool));
}
IEnumerator SomeCo(ref bool condition, float wait = 3f)
{
timePassed = Time.time + wait;
yield return new WaitUntil(() => Time.Time > timePassed);
condition = true;
}
There are many ways you could do more-or-less the same idea, that may be one that could let you reuse "SomeCo" for all 3 bools, unless specific logic differentiates them where you may need slightly different logic
hi guys. i have a button system where i use time.deltatime to scale buttons depending on wether or not mouse collides with them. when i pause the game using Time.deltatime = 0 command, my button code becomes useless (doesn't scale the buttons at all). short question would be: when i set time.deltatime to 0 to pause the game, what alternative system can i use to replicate multiplying by time.deltatime?
Time.unscaledDeltaTime
this is the best discord server ever. second time in a row a random guy just solves my problem with one simple sentence. thanks
Hello, I'm developing a zombie survival game in the style of Call of Duty zombies with my classmates and there is something I'm curious about
In my gun script I'm using 2 variables for certain values, such as damage, headshot multipliers or different ammo values (current ammo, max ammo etc) since I want to be able to change these values on the fly for various different reasons, is there a way to handle this more efficiently or is this good? I can show code if needed
is there a simple way to truncate a float?
i worry that the last digits will lead to imprecision in physics system, so my idea is to truncate position components to like 10^-6 every frame
Mathf.FloorToInt?
i currently have Mathf.RoundToInt(num * 10^6) * 10^-6
Yeah, I assume that's the simplest way of doing it
but i worry idk if this will really work properly on values on the order of 100 vs 10^-6
floats get 23 significant bits, which is worth 10^6.9 in the significand
Imprecisions are everywhere anyway
10e-6 is small enough to not be noticeable
It's built-in, due to how floats are represented
i just want to make sure I don’t actually fuck with my number outside of truncation by doing this, if my number is too big
And the best way of doing it, is to not do it at all
10e-6 meters is one micrometer, pretty much invisible
man, I took a class on this, and i don’t remember the fine details. I thought I would get 10^-16 difference in machine epsilon
but floats aren’t spaced like that 🤷♂️
Youd need to show code if theres some performance issue, which I doubt there is. The profiler will tell you if so. All it sounds like is that you've stored variables in a class, so im kinda confused what the question is really about tbh
i’m not worried about the difference being significant, but that the code for truncation doesn’t actually truncate due to side effects
No there is no performance issues I just wanted to know if it's good practice or not
As long as it fits your need and doesnt cause massive headaches, it's as good practice as you'll need
I would keep some immutable values to work with, and calculate based on thos
public bool isReloading, headShot, powerUp;
public float rateOfFire, damage = 25f, rof, fireDelay, headshotMultiplier, range;
private float internalDamage, internalHeadshotMultiplier;
public ParticleSystem muzzleFX;```
This is what I have
like totalDmg = fixedGunDmg * multipliers;
I'm using the "internal" private floats to do the calculations of damage and such
It is common to use scriptable object to store some initial value, then load the data from the SO. But this still means you store the same things on the gun
The public ones I use to set the value in the editor and to have a value stored to go back to after a powerup ends
try not to mutate values that you plug in during inspector
like this
It'll definitely mess with big numbers. Multiplying something by 1 million is going to decrease the precision significantly. At some point, stuff like 1_000_000_000 + 1 == 1_000_000_000, and it gets worse as you go bigger
hah i ended up having to use this to access the hp value of the enemy to create an instakill effect
There's an empty gameObject in the scene that just has the script of the enemy hp
That sounds more like something that's bad practice instead of anything with this gun script
how else am I supossed to get the hp value from the enemy at any time
It's not a fixed amount
the enemy gameobject should have a monobehaviour with its current status
The enemy should have some method somewhere, where it takes damage. Inside that, it should have access to the health
I already tried accesing directly the hp in the enemy but that has it's issues
For once if there are no enemies in the scene the script for the instakill powerup just doesn't work
You shouldnt be accessing the enemy hp as a bullet (using bullet as example). You should just be calling some method saying "I wanna deal this much damage" and then the enemy processes that
Ah, wait actually
I think I could just have the hp value be in the GameManager
this boy is going to need more help, bawsi
Unfortunately I must go soon but I suggest trying to get away from any solution where your objects that deal damage, know how much hp the enemy has. Unless this is like a mechanic of your game where X targets the healthiest Y
A bullet would do something like
If I collide with something that can take damage
GiveDamage(x)
That something that receives damage, processes it and can adjust their own health float. This now helps centralize armor calculations or block chance for example
That is what the enemy script is doing atm
If that's what it's doing then nothing should need to know the enemy hp. You can make another method to deal % health damage and then just send in 100% as a value
Or just an instakill method if 100% is the only percent used
so, you have a relationship between one instance of A and one instance of B, right? Like player-enemy or bullet-enemy.
Both A and B need to know about themselves. This would normally be a reference to an immutable scriptable object that has specific values that apply to any of that type (eg bullet is tied to a M16 gun asset, or Rifle gun asset, all of type Gun : ScriptableObject)
Both A and B ALSO need knowledge of their current state in a separate script (probably in a monobehaviour). This is something like currentHP (in monobehaviour) vs maxHP (in scriptableObject. monobehaviour reads maxHP in scriptableObject to initialize…)
follow so far?
Now A and B need a way to interact with each other. Which would be like a method in B that can read info in A and in B, and can then change B’s state based on it.
eg B has a script with DoDamage which takes in info from both A and B. Like
DoDamage(Gun myGun) {
currentHP -= myGun.baseDamage;
}
understand?
gtg now or my wife will kill me
I am not using Scriptable Objects and I am calling the function to reduce the enemyHP directly on the function that handles firing (Using raycasts)
fellas, quick question. is it possible to have an animation in a 9 tile sprite? so having the edges be as normal and have the middle tile be animated?
Alright so I just changed it to call the death function if instakill is enabled
the easy way would be to draw the 9 tiled sprite inside the whole thing for each frame. then 9 slice each one, and assign each like a normal animation
what i want to do is a conveyor belt with an animation. i want to be able to stretch it to any length but still keep the middle part animated and looking normal
there might be a better way to do that but im too dumb to think of one atm
you could make 2 gameobjects. one with a 9sliced static background, and one on top with an animated normal sprite
thats what i did
figured out like 15 minutes after looking at this
but thanks anyway!
Got a question about jobs, is it okay to access structs outside of a job or should you place them inside of the job itself?
Don’t understand, can you give an example
I just started working on a 2d top down shooter and ive given my player a rigidbody2d (on kinematic) and a box collider, and the walls have a box collider, but i can still move through them, here is my code in case its needed
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float speed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, Input.GetAxis("Vertical") * speed);
}
}```
Are they all using 2d colliders
And are any of the colliders marked as trigger?
no
ye 2d box collider
so i need to make the wall rigidbody2d on dynamic?
Are both the walls and player kinematic?
the walls only have box collider
I think it's your player that needs to be dynamic
yeah but i dont want it to fall
my player just falls slowly like that
my player is a circle if that matters at all
oh putting gravity scale on 0 seems to make it work
thank you
i do have another question though
how would i make an object rotate around the player by aiming at the mouse?
Any expert on ML Agents?
#archived-machine-learning
And best just ask the question instead of asking if anyone's an expert.
Good luck!
Thanks!!
What's a good way to store a bunch of interfaces that are implemented on a bunch of different classes throughout different namespaces. An example is my EntityRoutine class that accepts objects that implement the IEntityRoutine interface. This interfaces is used a bunch through different namespaces such as EntityAbility, EntityEffect, EntityConditions, ect, so it's quite popular. I've a bunch hanging out in global space I want to clean up is why I ask.
Make a "Core" namespace or place it in the namespace that it has the most cohesion.
Ah, yeah maybe something like just a general Entity namespace
then have these sub-namespaces inside of it
Would ask something similar to some enums but I think that applies to it as well
Also, a suggestion would be to get rid of the Entity name
I'm not expecting to see other type of ability
Are children guaranteed to be alive during awake or can I not count on that?
Alive?
like created. I get that if I'm referencing a different object during awake it might not exist yet. But does that also apply to children? Can a script in a parent assume its children will already be created when parent awake is called?
Do they exist in the scene or are you instantiating them ?
they exist in the scene
or if instantiated, they would be a part of the prefab and implicitly instantiated from the parent being instantiated
Might want to ask yourself why you have more than one namespace.
You control your namespace so you can always resolve collision through renaming, which is going to be a lot clearer than allowing the same name to exist in two namespaces in the same project.
hey! I'm making a game with input fields, I'm a starter so I don't really know much, so like I have it if its a string that it needs to be then it shows the gameobject, I aalready have everything but the script isn't really working, the text is equal as the string but it still somehow sees it like not equal (its a string "number")
Here is the script:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public InputField inputField;
public string desiredString = "1";
public GameObject correctObject;
public GameObject incorrectObject;
private void Start()
{
if (correctObject != null)
{
correctObject.SetActive(false);
}
if (incorrectObject != null)
{
incorrectObject.SetActive(false);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
{
CheckAndShowObjects();
}
}
void CheckAndShowObjects()
{
if (inputField != null && !string.IsNullOrEmpty(inputField.text))
{
if (inputField.text.Equals(desiredString))
{
StartCoroutine(ActivateAndDeactivateWithDelay(correctObject));
Debug.Log("Correct!");
}
else if (!inputField.text.Equals(desiredString))
{
StartCoroutine(ActivateAndDeactivateWithDelay(incorrectObject));
Debug.Log("Incorrect!");
}
}
}
IEnumerator ActivateAndDeactivateWithDelay(GameObject targetObject)
{
if (targetObject != null)
{
targetObject.SetActive(true);
yield return new WaitForSeconds(2.5f);
targetObject.SetActive(false);
}
}
}
please help me with this asap, I tried so many things!
dont cross post
bro like I'm trying to make a game and i'm a beginner, so like yea... i'm trying to get help asap
try log the string in inputfield first
uhhh.. how to do that :/
and like how do you mean that i don't really understand
I'm new
Log($"entered: {inputFielt.text}")
where do i put that
before comparsion
in the "check and show object()"?
yes
so like before the "if"?
yes
log is just showing you what is the text doesnt affect any logic after it
and it prints the right number that I entered
ik
i doubts that maybe some hidden chars eg zero-width space, in this case i will loop the string
i just realize that it is not TMP inputField
yea its a legacy
do i need to put it as tmp?
just keep this one should be fine...havent used this before
alr
so, what should I do?
based on the posts i suggest you use textmeshpro inputfield first
yea i tried rn
but it doesn't let me put the tmp input fields in the script
like if you know what i mean
in the inspector tab
do i need to change something in the script, so then I could?
yes you need to change it to TMPro.TMP_InputField
or using TMPro; then get rid of the "TMPro."
so i need to change that here?
public InputField inputField;
yes