#archived-code-general
1 messages · Page 16 of 1
unless you were able to simplify it in some way by placing a constraint on the system (like for example, nodes will only be directly adjacent to each other in cardinal directions)
what couldve caused this distortion in cosine
mhmhm yea I wanted to use raycasts to see which tiles the pawn can move to
So i have this code that is suppose give in index number out but it always gives 0. Here is the code:
private Color GetSkinColor()
{
int colorIndex;
int numberOfUnlockedTools = toolManagers.Where(tool => tool.Value.isBought == true).Count();
colorIndex = Mathf.FloorToInt((numberOfColors / numberOfTools) * numberOfUnlockedTools);
print("colorIndex: " + colorIndex + " = (" + numberOfColors + " / " + numberOfTools + ") * " + numberOfUnlockedTools);
return colorSpectrum[colorIndex];
}
And here is the print:
does anybody know what it is I'm missing
Integer division
25/38 is 0
ohhh, i see, thanks
How do I assign a value to a variable only if its undeclared?
What do you mean "undeclared"
You cannot assign to something that is undeclared
sorry, I mean not assigned a value.
It's declared just hasn't been assigned anything
For float you can't really tell that
You'd have to use a nullable
value types are not null when unassigned, they are their default value
really? that seems weird
That kind of condition is not supported as the compiler cannot know where it has been assigned
for example, by default, floats are 0
Why is it weird
They're basically primitives they can't be null
You could use a nullable if you want
ah ok, but theres no way to tell if it is default 0 vs set to 0?
Anyone know what couldve caused it?
transform.position += transform.right * Mathf.Cos((Time.time - startTime) * projectileFrequency) * projectileAltitude;
is what i have
should be fine but for some reason there is some weird offset
float? myNullableFloat;
Shouldn't do this additive thing
Nullable or use flag like bool isMyFloatSet
Can you show more context
what is the default value of that then?
null
oh right. start time is simply time.time in Awake function
null? and does it act like a float other wise
more or less...
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types
That's so cool! I always wondered what nullable ment
Ah shoot, so its not that easy. ofc it isn't lol.
You shouldn't do it like this.
You should do:
Vector3 startPos;
float time = 0;
void Start() {
startPos = transform.position;
}
void Update() {
time += Time.deltaTime;
Vector3 currentPos = transform.position;
currentPos.x += Time.deltaTime;
currentPos.y = startPos.y + (Mathf.Cos(time * projectileFrequency) * projectileAltitude);
transform.position = currentPos;
}```
trying to additively do this won't be consistent
Yeah you should make it relative to initial position
I can cast it, but its a little annoying
Not accumulation
just need a .Value
oh, that makes a lot of sense actually
thank you so much, ima take my time and try to understand it
What would .Value return if it was null though?
NullReferenceException
Note that this, or accessing .Value if the nullable is null will throw an exception. If you need to pass in a default value if the nullable is null, you can use this handy syntax: nullable ?? defaultValueHere
Straight from the docs
?? returns the thing on the right, if what's on the left is null.
Ah it's InvalidOpertionException 😄
Jesus, I thought this was a quick and easy question, why do floats gotta be so weird with nulls
ok thats really handy to know tho
it's a very quick and easy question
you're overcomplicating it tbh
I have a problem, I'm getting a null reference on this line https://i.imgur.com/JQO4ZsX.png, and its the Gamecontrols part of the code, that gives a null reference, but its not doing that for a different script with he same line of code.
are you kidding me
Remove .Value there
Well don't access .Value in this case
Which line
the start of the If statement
what is the .Value returning then if not a float?
Nothing, you get an error: InvalidOperationException
Gamecontrols is null most likely
you'd have to show where you assigned it
Ok thanks, I don't even need null safety here cuz it will be set in Awake() but that's super useful to know thanks.
that's not assigning it
that's just declaring it
The code that isnt working in this script, is working in other scripts though, so i'm not sure why this script cant find my inputsystem
you aren't assigning it in this script
you are in the others
oh ok
Assignment needs the = operator.
This error only happens, in my build, not in the editor.
Why don't you just show where you're assigning it
so we can rule that out as the problem. So far I can only assume you just never assigned it.
What is InputManager.inputActions and where is that assigned
oh right, i remember the issue i ran into about when using relative to initial position, like X and Y is fixed in the world, but is there some method i dont know about that could kinda make it relative to a certain vector
something along these lines
dont know how to formulate the question to google it haha
input actions, is the name of my asset
ok but
that field
it's a static field?
How and when is it assigned?
How do you know that assignment is happening before this code runs?
proobably just a script execution order issue
Go to the InputManager script
You can still use transform.right and transform.up to represent local XY axis in world space
show how and where inputActions is assigned
oh alright thank you
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
rigth so
as I said
it's just a script execution order issue
private void Awake()
{
if (inputActions == null)
inputActions = new GameControls();
}```
This is running after your other code
so it's still null when the other code runs
oh ok
Recommend just getting rid of is code entirely. Just use a lazy property e.g. private GameControls Gamecontrols => InputManager.inputActions; delete the rest
So delete the Onenable and Ondisable code and just put ^ this code?
I think its working
o almost got it
just projectile stands in place now lol, but at least the sine is right
Yes it's working thank you.
oh right, because i used rigidbody force as forward movement
when changing transform.position directly it doesnt quite work now
hey guys , i can use some help breaking my head over this for hours. my raycast drops my game from 60 to 30fps or worse. what could be the cause if anyone stumbled upon something similar?
I have a problem, so I have some things you can unlock, and some of them makes a popup show. The current way I'm doing it is every unlock have a variable that is isBought which become true when you buy it, the the popup system runs every frame and looks if the specific unlock is unlocked, and if it is it shows the popup.
The issue is now it of course keep showing even after I close it, as it is still bought. How do I fix this?
I cant change isBought because I use it in other places…
link the closing button of the popup to a function that sets the popup inactive and sets the isbought false
how many ms does that take up?
have you tested that in a build?
if(item is bought) => popup.setactive
than make the button linked to a function in the same screen that has a function like
popup.setactive(false)
you dont even need the variable for that
about 3.4ms
ahh, ill try that
mind you im running the profiler on a pc for a game meant for android. on the phone this raycast is so bad it makes it go BURRR
for 60 fps each frame is 16.7 ms
and for 30 its 33.3
so your 3.4 ms is probably not the cause to drop from 60 to 30
its exponential. the game allows for creating a bigger level. the bigger it is the harder this ray sunks the performance
Hey Guys,
I'm desperate for anwsers and apparently equally incompetent.
What on earth is causing GC allocation in this code:
public static bool IsConstructionPiece(this Piece piece) => IsType(piece, snapNodes => snapNodes.Count != 0, Type.CONSTRUCTION);
Calling:
private static bool IsType(this Piece piece, Func<List<Vector3>, bool> isType, Enum type)
{
if (isType.Invoke(primarySNs))
{
//Debug.Log($"Piece '{piece.m_name}' { piece.transform.position} IS a {type} piece");
return true;
}
else
{
//Debug.Log($"Piece '{piece.m_name}' { piece.transform.position} IS NOT a {type} piece");
return false;
}
}
(yes - you are correct - the commented out sections cause the Enum type parameter not do do anything)
while primarySNs refers to a simple collection variable, and Type.CONSTRUCTION is an enum value
I have a lot of these "IsSomethingPiece" calls -> calling IsType under the hood. And all of them allocate quite a bit of trash.
But more importantly than improving the performance I would like to simply understand... why does this allocate?
Is this some wierd-ass clojure magic due to me dragging in a constant enum value? Is this due to extension methods... somehow? Is it the work of the devil?
Graphics raycaster should only care about the UI
so very complex ui you have?
do you have experience with maxSDK? could the banner cause something like that?
I don't understand, the first one works fine but the second one tells me that using new on a MonoBehaviour class is not allowed. What's the Difference here? I just want to store data but im not allowed to make a new object to hold it?
there is alot of UI but they all are inactive during play
i have not
but if that a possible cause that should be easy to test
inactive as in the Canvas is not active?
yes. during play all canvases are set inactive. only simple 2D sprite objects are rendered
You cannot use new on MonoBehaviours because that would mean creating one that isn't attached to a Game Object.
You can use new on PopList because it's not a MonoBehaviour
so no graphics raycaster should be active at that time
thank you for clarifying only UI can cause it. it might be the ad banner causing it
PopList is a MonoBehaviour and so is Bubble but making a new Bubble doesn't error
Then Unity isn't picking it up
Either way you should never use new on anything that derives from MonoBehaviour
oh shot really? thats like all my code
If it's not meant to be attached to a Game Object directly, don't inherit from MB
then it tells me this
Yeah that's a result of using new on MBs
Or trying to attach a script that isn't a MB, onto a Game Object
No that only happens when I remove the : MonoBehaviour
Yeah because now it cannot be on a game object anymore
If it just stores data, make a plain class
Then how would it execute if its not on an object?
Oh cuz its not mono
It wouldn't execute yeah
You would do stuff with it, from other scripts that are MBs
Erg so I have to decide between a data structure and a Unity Runtime structure
I want an encompassing objects to store all its children in a list to save
omgosh, this linking between class objects and monobehavior objects is making my head hurt
@leaden solstice @leaden ice just wanted to thank you! managed to figure out how it works and make it work as well
Cat power
🐱
Hi. I'm trying to make a zip line the player and the AI can go in and out of. problem I run into is that the AI can go in but they can't get out. I tried measuring vector3.distance for the line to let go once the AI reaches point but no go.
any suggestions?
hi guyzzz!!! how do i read how deep i am i to a collider O_O
how should i logically handle a character system
i want 4 different chooseable characters or classes, each with heavily varied gameplay
and im not sure how i should handle everything from the playermodels to the code that controls them
should i try to set up a base character controller that can use a public variable to determine what class it is controlling? should i store each playermodel indevidually or use a base playermodel and try to tweak it to fit the appearance i want for each class? should i have an items system to determine which item each character will start with or should i hard code it into the character controller considering that you wont be aquiring any more items?
why doesnt the Mathf.Clamp do anything
clamping the value doesn't mean anything if you aren't using that value to assign a specific rotation. all you are doing with that value is putting it in a Vector3 then using that vector's magnitude to rotate the object.
you should search "clamp camera" in this discord to find examples of how to correctly clamp the rotation
and don't crosspost
when i search clamp camera it just comes up with people having hte same issue
yes well you need to go back further and click examples
I'm currently using JSON.net but when i use jsonconvert.serializeObject I get a self-referencing loop error. Strangley this only happens when the class contains a vector2 variable... how do I fix it?
Hey quick question, is JsonUtility.ToJson() recursive? meaning if i have a gameobject with a list of gameobjects with lists, will this turn all of that into one json or do I need to manually pass up json data?
why are index buffers not available in builds for meshes that dont have read/write enabled?
like in a speculative sense or how can this be worked around?
yes
i think it has something to do with the graphics apis
and read/write really means whether or not a unity object is given to you representing the graphics resource
because in order to make that work, it has to do some kind of synchronization step that is potentially slow
so wait why are they available in editor but not in builds?
i have a script called score on 2 game objects how can i do that a variable has the same values?
I'm not 100% sure what you're asking but from what I guess I think you need static variables
Do you mean, making two floats match?
i have a score display that shows my score. when i die i have another score display but it says 0
Just get the score from whatever is storing it, or am I not understanding
Are you saying you have 2 prefabs that need to share the same float, if so then make it a static float that gets updated
yes that probably i just didnt want to make a new script for only one purpuse
it would be a bug when those are different. however not necessarily a unity bug
it may appear to be the same mesh in editor
not 100% sure
how
when i run into issues like these it's never "because the editor is using the single threaded graphics device and player builds are multi-threaded / native jobs"
it's very very rarely "because the editor is dx11 and the device is opengles 3"
public class PlayerHealth : MonoBehaviour
{
public static float health=100;
}
index buffers sound too normal for that to be the issue
hmmmm
you can make sure your device and editor graphics apis are exactly th esame
a static variable is one that is shared among the class. So its like a globaly shared value, exectly for what you are trying to do
including unchecking multithreading
which will worsen performance possibly significantly
again, if I make the mesh read/writeable in editor and build, the index buffer is available
if I dont make it read/writeable its not available
im running dx12
how?
what device is it? i suppose just eyeball it
you'll bea blet o see
the windows editor supports opengles3
oh i fixed it, it was the semi colon on the if statement
device?
3080 mobile?
hmm
now it messed up this csharp scoremanager.GetComponent<score>().score_count++
no meant GraphicsDevice as in the graphics api
which yes it sounds like it's the same
ahhh
i think its' some other bug and this is a red herring
unity thing or is it something in windows
if you just use a static variable then all you have to do is score_count++; Are they the same class? if so because the variable is static, they are linked. So when you update it on one, it gets updated universally
different class
Static member 'member' cannot be accessed with an instance reference; qualify it with a type name instead
ah, then you might want to make the score manager a static class so that you can just do scoremanager.scorecount
Graphic api is dx12
if you're not familiar with static classes/variables then I would recommend you read up on that. They are useful
also do you mean static score class? thats the class name with the variable. score_manager is just a "container"so im told
sorry yes, you can just do score_manager.score or whatever because the class is available and you are accessing the class variable. Here's unity's guide, but they're pretty simple: https://learn.unity.com/tutorial/statics-l#5c8920e7edbc2a0d28f4833c
They give you an example on that first slide there
2021
I need the UAV count of dx12 for other shaders
but the error is on the CPU side
saying that the index buffer is null
I... cant run my project on dx11
Quick question, is it better to use a timer variable and subtract from it time.deltaTime to wait for a certain amount of time or is it more performant/simple to use corroutines?
It depends
have you tried upgrading
I have not, the thing I am making is for others to use
If this timer is not going all the time, a coroutine might be better to avoid having an Update.
But coroutines have their own costs - like garbage collection etc.
If the timer is going all the time Update is both simpler and cheaper
Hmmm ok could you give an example
Like for a jump pressed buffer it would be best to use update rigth?
probably
And couroutines for something like a loading screen that works similarly to the time-line package and that needs to be called just once?
if this is my movement code
GetComponent<Rigidbody2D>().AddForce(transform.up * jumpForce);
why do i get a boost if i colide with 2 things it jumps higher (edited)
when colliding with platform
you die
Because it adds a force twice
How can i fix? Should i always set force to 0 before applying the new one?
Okay
And also how can I duplicate a game object through code? (A different game object not the one with the script) I’m trying to make a self generating level
My idea was to duplicate a platform every few meters and have a random X level in a range idk if it would work
GameObject newObj = Instaniate(oldObj, newPos, Quaternion.identity)
Thanks now can you please explain what each word is? I’m a beginner sorry
Probably should have asked this in #💻┃code-beginner then
But you can use the docs to look up what Instantiate does, or what Quaternion.identity is
Okay my bad
I have a strange issue with the vertical rotation of my 2D character. I am using Unity's new Network for GameObject system. For example, when I flip my character on the X axis in my client, look how it acts on the host's screen. It flips like a sheet of paper, a bit like Paper Mario. It only does this when the Interpolate option is checked. I am having a bit of trouble understanding what to do to fix the problem. I have made a little video for better understanding: https://www.youtube.com/watch?v=xZeNciB7zfo
This is a limitation of the interpolation. You are better off syncing a bool for "isFlipped" and applying it to the spriterenderer in your own code
Opposed to syncing the scale automatically
@neat lagoon, so it's better to turn off synching of ScaleX ?
Yes
Okay I understand, thanks for the fast reply, I'll try that! 🙂
Anyone know what would be the preferred way to make a combat log/chat would be?
I'm wanting to use TextMeshPro so I can include symbols, and would ideally like it in a standard scrollable log
But as more text gets added it causes framerate spikes (my actual framerate is ~800, but adding text can take it down to ~8 for a few milliseconds). This is definitely noticable as it freezes the whole game (I can't thread off TMP)
I have seen some mention of this being down to TMP resizing and that it should be fixed (back in 2018), but other than that I can't see what a likely cause may be. Does anyone know of a good TMP chat/log tutorial? It feels like it would be a pretty common thing for a game
Did you try profiling? I assume you instantiate a new TMP for each line? Try using one component for the whole log.
I'm using one component. I have turned on profiling, but honestly I am not familiar enough with it to know how to track anything specific
like, it happens for roughly half a second every 10 seconds
(Half a second is generous, more like 100ms)
I was going to try multiple components, but the replies on stackoverly make me hesitant to try otherwise, though I can't imagine a text variable gaining more and more lines would do well long term?
(speaking on the current one-component setup)
See the frame graph. Identify spikes. Select a frame with a spike. Check the hierarchy view sorted by CPU time. Expand the most time consuming branch.
I'd suggest to use the profiler to figure out the cause first before attempting any fixes
Apologies, as I said, I'm not familiar with this at all really. DO you mean the frame debugger, or the CPU usage frame-by-frame in the profiler itself?
The CPU profiler.
If you're not familiar with it, now is a good opportunity to get familiar.
Yeah, I was trying, I feel like I do get stuck on the simplest points tho. Like, how to go back frames
It says I captured 20k frames, but I can only see the latest ~300
Yeah, you can only see the data for the last several hundred frames. Captured frames is simply to get an idea on how long the profiler was on.
You can increase the max kept frames in the editor preferences.
Garbage collection.
And one with actual column names... 😛
Yeah, it kinda is. I have no idea where it comes from though
Hey just want to check, is the GetComponent<T>() a read only? or can I use a JsonOverride to set all values at once.
the scene has.. like, 3 spheres in it and the chat
Wdym by read only? It returns a reference to the actual component, so you can access it's field, properties and methods and write to them if they allow it.
Well it's coming from the TMP. Can you take a screenshot of the TMP text inspector?
So are you able to do thing.GetComponent<thing>() = newComponentThing
No. That you can't do. Not just with component, but in C# in general.
Or any language that I know...
idk why I was thinking about it like a clas
I mean, the obvious answer is... it's a good chunk of text and most of it gets masked off, but.. it's one component getting assigned all the logs
Aah. I bet it's the hypertext tags. Tmp is parsing the whole string and processing them, creating a lot of garbage in the process.
In this case splitting it into several components is probably the best option.
Ohh, not what I was considering at all then xD
One for each line. And you can use a pool of text objects.
So have a list of text and push them into a limited set of components?
Correction: when I said "split into several components" I actually mean "split into several objects". I think that was obvious, but just in case.
Yep.
like a list of 20k lines, but only 20 actual components being assigned the text?
based on scroll*
Yep.
I'll give it a go, thanks a lot for that
Any advice for a more.. customised scroll bar?
Customized in what way?
In that if I have a fixed 20 components, it won't have an actual relative scroll, right?
I'll just be cycling 20 objects
Aah
Or am I getting this wrong?
Indeed. That would be a problem.
You'll need to customize the scroll bar for that, you're right.
I'd start with researching how the normal scrollbars works and figuring out if you can actually adjust it to your needs via code or you'll need to code it from scratch.
Cheers for that. Also, is there a way to run the profiler on a build game? I'll look it up if it's not a simple answer
but I figure I may as well check what it does with an actual build for GC
oh hey @cosmic rain , by the way remember when we couldn't get Unity to work? well I submitted a ticket and after 2 weeks of them not replying I opened unity to keep troubleshooting and it just worked. not a single error. not a single project that wouldn't run. I thought they put out a patch or something but then they got back to me and offered a new binary to try but I told them that it magically fixed itself.
It's possible. The simplest way would be to build a development build and connect your editor profiler to the build.
Thank you again, Really appreciate your time on this. It might seem simple to you, but I was banging my head over it 😛
Hmm... Then it was probably something with your environment. Maybe a sneaky windows update fixed it or something.
yah idk cuz i didn't touch my pc for 2 weeks
If I try to stop my coroutine does the parameter matter? Does it have to be the same as it was when I started it?
You don't need parameters to stop a coroutine. If you do, then you're doing it wrong.
Thanks
Just to clarify: you don't stop it the same way you start it. You need a reference to your coroutine instance to stop it.
You helped me to remember, yeah
So if I stop my coroutine, at what point will it stop? At random point in the coroutine or at the yield?
At the yield. Coroutines run on the main thread, and there's only one line of code executed on the thread at every given moment. Unless you call stop coroutine from within a coroutine.
In the latter case it would still probably get to the yield.
I have a quick question. When we try to run the game in the unity engine it runs fine, but when we build and run it, the triggers don't work. We have been trying to figure it out for hours now... Any Ideas?
Are there any other differences (platform etc)? Also not a code question, try #💻┃unity-talk
No other differences we could find, and we aren't sure if its unity or if its code :/ i'll ask there tho
I have text that is supposed to be shown on a screen. the only issue is I was hoping I could apply a fisheye filter to the test to simulate the rounded screen. how could I do this??
not a code question #💥┃post-processing
I have some annoying stutter on my player when he moves. I think it is caused by my movement script but I cant figure it out could someone have a look? And I know the script is a complete mess.. https://paste.ofcode.org/ZgWYrtq6qXscp2J6WNE4as
make sure interpolation is enabled on the Rigidbody2D
the settings I use
how are you handling camera follow?
I currently use my own script but I also tried Cinemachine and had the same Problem
Can you show your script?
yeah wait
(I do recommend Cinemachine 😉 )
Hi guys
Wanted to ask
Is it correct to use UnityEvent to handle input?
As you wish
Thanks mate
in what way? What do you mean by "correct"?
I mean if I should do it
What kind of input? How exactly is unity event related to it?
the question is too vague ¯_(ツ)_/¯
Can UnityEvent somehow be involved in input handling? Sure.
depends on how you're using it
what you're doing
etc
If i detect some input I call some action
Ok what would be a problem with that?
Like what?
hey, what does this error mean?
Like it don't being as fast as I need
wdym by "fast"? It's fine
It is a fps test, so it shouldn't feel laggy or something like that
It should feel instantaneous
why wouldn't it?
You think invoking one UnityEvent is going to have impact on your framerate??
if you're really concerned, do it and check the profiler
you probably won't even be able to find it
Wellp, that's enough for me
If invoking a single UnityEvent in a frame was a problem they wouldn't even be in the engine
Thank you mate!
And have a good night
void Update()
{
if(throwable != null && Input.GetMouseButtonDown(0))
{
throwable.DisableObjectGravity();
}
if(throwable != null && throwable.beingCarried)
{
UIManager.Instance.AddInfo("THROW (RIGHT MOUSE CLICK)");
if (throwable.touchWall)
{
throwable.EnableObjectGravity();
UIManager.Instance.CleanInfo();
}
if (Input.GetMouseButton(1))
{
throwable.EnableObjectGravity();
throwable.rb.AddForce(playerCam.forward * (throwForce * Time.deltaTime), ForceMode.Impulse);
UIManager.Instance.CleanInfo();
}
}
else
{
Ray ray = new Ray(playerCam.position, playerCam.forward);
RaycastHit hit;
Debug.DrawLine(ray.origin, ray.origin + ray.direction * pickRange, Color.green);
if (Physics.Raycast(ray, out hit, pickRange) && hit.collider.CompareTag("Throwable"))
{
throwable = hit.collider.GetComponent<Throwable>();
UIManager.Instance.AddInfo(hit.collider.gameObject.name + "(LEFT MOUSE CLICK)");
}
else if (throwable != null)
{
float distance = Vector3.Distance(throwable.transform.position, transform.position);
if (distance > pickRange)
{
UIManager.Instance.CleanInfo();
throwable = null;
}
}
}
}
hey guys, since TriggerEnter and Exit are more expensive than using raycasts, I changed my code to help with that. But the problem is that the ray doesn't move from place while in play mode, although in debug it moves correctly like I want to (maybe Update updates differently from DrawGizmos?). Can someone help me fix this problem, which I think is due to the parent of the camera - because when I move it the raycast also moves but I don't understand why and how can I fix it. Thanks!
yellow represents the debug.drawray and the green the current state in update
also hierarchy
since TriggerEnter and Exit are more expensive than using raycasts
That's usually not the concern when deciding which of those two to use but ok...
Ray ray = new Ray(playerCam.position, playerCam.forward);
Your ray is explicitly being drawn from the camera's position in the direction the camera is facing so of course it depends on the camera position.
I don't understand the second point, it works while debugging why not in play mode?
wdym by "while debugging"?
how is that different from play mode
That's why I made this post. As you can see in the code I posted, I created a ray that should update based on the playerCamera. I tried debugging using Debug.DrawRay on the Update function (the green ray on the video) and also in OnDrawGizmos (the yellow ray) and you can see that they display different results although I'm using the same code
show the code for OnDrawGizmos
show the whole script
word limit
it only has this more
{
Debug.DrawRay(playerCam.position, playerCam.forward * pickRange, Color.yellow);
}```
its just this
I mean pretty sure those are equivalent but why didn't you just literally write the equivalent code
ALso you don't need to use OnDrawGizmos for Debug.DrawRay - it's only for Gizmos.DrawXXX stuff
I had it the same before changing to what it is now, I tried to do several things
it's unclear to me why in your video it doesn't look like the camera is moving around
it looks like a light is moving around
I'm guessing you have just mixed up an object reference somewhere
it's a flashlight, the camera moves on play mode
and seeing the rest of the code may help
Also knowing which object in the hierachy is assigned to playerCam
the main camera
That's all the code for that script
I wish I could explain it better to you but I don't know what else to say lol
^
Also making sure you've assigned the camera correctly
and knowing for sure there isn't another copy of this script in the scene
etc
What code do you want? Do you want a specific script? The script is all there
I checked everything
You missed something, that's why you're here
It's all right
Do you want help or not
But it has nothing to do with the hierarchy or not assigning correctly, I'm sure of it
People have been sure of things before and been wrong
Do you have any other copies of this script in scene?
How have you confirmed not?
Of course I want help, that's why I came here, I'm not trying to be rude
I'm also not trying to be rude, just asking for more information so I can help
Because I checked all the objects and none of them have this script except the player
how did you check
just manually?
yeah
Have you done a t:MyScript search in the hierarchy?
Have you done this search at runtime?
just do it while the game is running
And you're sure there's only one copy on the player?
I'm pretty sure it has something to do with the parent of the camera
yes
i'm going to send a video and try to explain
I mean one possibility is your camera in Update is being reset to the identity rotation and then some other script such as CM points it at the target
any scripts which deal with camera rotation might be helpful to see
Ok, so as you can see when i change the rotation and position of the CamHolder that is the parent of the Main Camera playerCam it also moves the raycast
right so... what scripts/components are involved with the camera?
I have a pretty simple MouseLook script that is on the MainCamera:
{
[SerializeField] private float sensX;
[SerializeField] private float sensY;
[SerializeField] private Transform playerDir;
private float xRotation = 0f;
private float yRotation = 0f;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
playerDir.rotation = Quaternion.Euler(0f, yRotation, 0f);
}
}```
you shouldn't multiply mouse input by deltaTime btw
The CamHolder that is the parent
it's going to make things stuttery
thanks, going to change it now
what is playerDir
you'll need to reduce the sensitivity variable to compensate, but it will become smoother overall
It's a invisible game object that points in the direction of the player
it's a child of the player
Orientation?
yeah
CamHolder has no components on it (other than Transform)?
that's what i was going to say now lol
it has a move camera script that makes the camera follow around the player, it basically just changes the position of the camholder to be the same as the camposition (child of player)
void Update()
{
transform.position = cameraPosition.position;
}```
I did this so the Player and Camera stayed separated
There's a component called PositionConstraint that will do this btw
Really? didn't know about it
I place it in the camholder or the camposition?
it replaces your small script here
and put the weight to right
it also handles offsets, weighted following of multiple targets etc...
anyway...
as for your actually original question, I'm still not sure 🤣
you're sure that green gizmo isn't drawn by a different script?
how to stop texture bleeding from an atlas in a minecraft game?
yeah im absolutely sure, it's my only debug.drawray that im using
Make sure mipmaps are disabled on the texture and point as a filter mode. If the bleed still happens, look at adding padding to the atlas
mipmaps on and off do nothing. turning it off seems to do the trick in the scene view
if (Input.GetMouseButtonDown(0))
{
while (Input.GetMouseButtonDown(0))
{
GunInfo gunInfo = new GunInfo();
float fireRate = gunInfo.fireRate;
StartCoroutine(waiter(fireRate));
items[itemIndex].Use();
}
}
Does anyone know how I can get the info of the current gun?
Certainly not like this. This is an infinite loop
also creating new GunInfo every single time
Wdym by "info"
ik
if you want information from something then it needs to be referenced
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "FPS/New Gun")]
public class GunInfo : ItemInfo
{
public float damage;
public float fireRate;
}
Ok but.mm Are you storing these in a collection somehow?
How are you associating these with different guns
And why are you writing a while loop
And why are you creating a new one
thats the whole script of this
I would expect a collection of GunInfo somewhere
Or at the very least a single reference to the current gun
wait
I can move it out of the player controller
into another script
that has the reference
the main script
that fires the gun
void Shoot()
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
ray.origin = cam.transform.position;
if(Physics.Raycast(ray, out RaycastHit hit))
{
hit.collider.gameObject.GetComponent<IDamagable>()?.TakeDamage(((GunInfo)itemInfo).damage);
PV.RPC("RPC_Shoot", RpcTarget.All, hit.point, hit.normal);
}
}
Would this work?
If I put it somewhere in there *
I am having trouble figuring out how to implement the network variable so that it is applied to all clients and the host. I want my 2D character to flip horizontally on all clients, as well as on the host. Currently, the host can move and the clients can see the host move, and the host can see the clients move. However, I am experiencing difficulty syncing the flipX for the sprite renderer across all clients and the host.
I'm pretty sure I have to do something in OnValueChanged but damn I can't find out...
If someone can help me, full code is here: https://forum.unity.com/threads/i-am-having-difficulty-understanding-networkvariable.1386966/
Hello. Anyone know some good tools to visualize ur code structure? I just want to see the hole simplified picture of my projects, with decisions I made and class dependences.
Apparently there's something called "dependency diagram" feature in VS. Might want to check it out.
Hi guys , please help. have a raycast performance issue. but i dont even use it. how can you find the source object the uses it? profiler doesnt mention any script/object
Enable deep profiling
Thats the ui raycaster...interesting why its taking 3 ms
It would seem that the raycaster is being called for every object in the canvas when you move the mouse for example. So I guess you have 179 ui objects. My solution. Split your ui into multiple canvases each with its own graphics raycaster and remove the one from the root canvas
That way it wont iterate over disabled objects
how many GraphicRaycasters are in your scene?
Problem found. I had many text prefabs instantiate with raycast component attached to them
Im making a game, and the main damage is throwing explosive projectiles at enemies
But as the game progresses, as i shoot multiple projectiles and hit multiple enemies
It get laggy
Do the projectiles despawn?
What in my code / project should i look at to reduce lag?
Yeah
In what way
Destroy
Hm
Maybe consider implementing pooling
I don't know the context of that reference
What?
What would that involve*?
Try adding pooling https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html
Profile the problem first. Currently your just guessing what the problem is.
Making it so that you don't Destroy objects, but set them inactive to reuse them first
My enemies are 2d animation based, but i use an image to check sizing
That's what I said but thanks for providing the docs
This is most likely not too related to pooling but it's a good idea to start with this
Yup
Oh right, didn't see lol
It could maybe be this but we'd require more context
If you could share code that'd help
Yeah im ok to share code
Its just that idk where to start
I could break down how i go about things
I don't know how large it is, but I'd just share the relevant code
Probably in paste sites by the sound of it
#854851968446365696 for that
Yeah ill do it after but ill tell u the gist of it first
Sure
So first I suck up a bunch of enemies, they are stored into a list.
I intend this to be a wave ebased game
Then shoot them out
But as a seperate projectile object
Are you using some physics query like Physics.OverlapSphere?
E.g. i suck up 6 enemies (set them inactive) then instantiate 6 projectile gameobjects
After the projectile game objects collide, they destroy itself, then instantiate the sucked enemy
Why are you pink now reee
Then instantiate an a explosion for each projectile collision that does damaage to each enemy hit
Roughly, how many objects are you creating at once?
So e.g. the 6 projectiles collide with a wall then 6 enemies are spawned in the collision place and then 6 explosions are
instantiated then destory + damage calculation
It's purple though 
So 18 objects
But it doesn’t lag at the start?
is that each explosion can hit each of the one enemy
so there will be 36 collisions
with explosion and enemies
Start with sharing the code?
#854851968446365696 at the bottom
^
^
Still, if you would profile it, you would know if the instantiation is the problem, the explosions effects, or the physics checks are the problem. Maybe a combination.
Im not quite sure
I think its the fact that this collision i sent
can happen alot of times
name.Contains doesnt look very good
Yuh, its my first time using unity lmao
(Regardless of any of this speculation, profile it)
I know my design and style is bad
Not sure what that even means 😭
I should be in beginner chat
Code for damagePopup?
if i reference something in a scene (in a script that is not in that scene) and then unload and reload that scene, will that reference still work?
Pretty sure the reference will turn "missing"
Hmm, maybe just use the profiler
Would add an Enemy tag to the enemies and then use .CompareTag("Enemy") instead of the whole name contains check
Nothing weird in these scripts
Pooling will definitely help if you have this instantiate often
Do u think it would lag
But it should not lag
if that code that to run in one instant like 40 ish times?
Also, instantiating world UI objects without a pool seems inefficient to me, afaik they are quite expensive.
So maybe pooling?
100% pooling
Like the best it can do is improve your performance
The worst it can do is still just have a better system kek
Yeah fair
So it’s a win win
How taxing is having to instantiate an extra image
Alright, i should do some more testing to delve into what lags
ill try taking out the damage canvas
also
and the hp canvas
to see if that changes anything
Profiler
O
Sorry I thought u guys were talking about note taking or something
Didnt profile was for checking performance
Apologies
Also do the compare thing Osmal said
Also i was making a mobile app
And the thing is about the lag, is that u dont usually lag until late into the game
And u cant get late into the game without playing on the mobile
LOL
I havent been doing much testing till recently
So i should just make some testing scripts
You should look into how you use the profiler
Yeah definitely
Maybe something is somehow hogging a bunch of memory
Since it is something long-term
I have one more main problem
So i had my designer design a start menu screen
And i was gonna add buttons overtop the menu screen he drew
Is it a coding problem
Yeah
Okay, fair, continue
Mobile are susceptible to overheating. When they do, they throttle down performance.
But Im not sure
High and often resources usage can make mobile devices heat up faster.
How to make the buttons stay consistent with the location of the menu screen background
Instead of relative to resolution
of the mobile screen
Im not sure if u guys get what i mean
Yeah, i think ive lagged testing on Unity before lao
Use anchors.
Yeah so i tried using anchors
Try harder lol
Does Unity have a way to calculate GPU VRAM usage at runtime?
Im running out of VRAM and need to cap it before the app just kills itself
Profiler?
But i doesnt make the button stay same position relative to the background image
What
Runtime on iOS I should say sorry
And it's user generated
So I can't predict how much will be used
NVM I see gotta anchor to the image
I told you 
hi guys, im trying to user the profiler to identify an issue in my code, but im not sure how to use it to drill further down into the issue, atm it just says this one script is consuming all the resources, but the update functional does a few things, is it possible for this profiler tool in unity to help me narrow it down further?
You can place profiler markers to profile specific piece of code. Check the Profiler page in the API docs.
But from the look of it, the issue seems to be with memory allocations, so it shouldn't be hard to identify the culprit.🤔
yeah like creating something over and over again, i reckon.. but i dont think i am..
Hello, i am trying to get the height and width of a texture2D but unity always limits the texture to 2048x1024 although I changed the MaxSize in the settings of the Texture to 4096. Does anyone know why?
I wanna get the real resolution of the Texture
I don't think this is code releated
I've got a question about inheritence, I don't quite understand how to work with constructors in combination with inheritence. I'm trying to run the inherited constructor, if even properly possible
This is currently my code
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class MainMenuButton : MonoBehaviour
{
public Button button;
public UnityAction onClick;
public MainMenuButton(UnityAction onClick)
{
button = GetComponent<Button>();
this.onClick = onClick;
button.onClick.AddListener(onClick);
}
private void OnDisable()
{
button.onClick.RemoveListener(onClick);
}
}
using UnityEngine;
using UnityEngine.Events;
public class Quit : MainMenuButton
{
public Quit(UnityAction onClick) : base(onClick)
{
onClick = Die;
}
private void Die()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
print("I quite the damn game");
#else
Application.Quit();
#endif
}
}
I'm trying to run the base in in the latter
But not sure how to
you cant use a constructor with monobehaviours its done automatically by unity im pretty sure
you can only instantiate a monobehaviour
So what I'm trying to do isn't possible?
i dunno what youre trying to do sorry
But if this wasn't a MonoBehaviour, it still probably wouldn't work because it looks like you're trying to set onClick = Die before the base constructor is called. : base(args) will run the base constructor first. There's no way to run the base constructor after the derived one.
But Sirix's point also stands. You cannot use constructors with MonoBehaviours.
Righty, thanks for the info
I suppose it's time for me to figure out a different approach then heh
If you instead have an Initialization method, then you can more finely control the order of things
Make it virtual in the base class and override it in the derived class. Then you can choose when to call base.Initialize(args) in the derived override
Yeah I suppose I could replace the constructor with a method like that
Yeah that was what I was thinking, thanks
private void Update()
{
Profiler.BeginSample("Unit Update");
GridPosition newGridPosition = LevelGrid.Instance.GetGridPosition(transform.position);
if ( newGridPosition != _gridPosition )
{
GridPosition oldGridPosition = _gridPosition;
_gridPosition = newGridPosition;
LevelGrid.Instance.UnitMovedGridPosition(this, oldGridPosition, newGridPosition);
}
Profiler.EndSample();
}
this code was fine previously and i dont think anythings changed but this is like 99.5% of the GC calls
public GridPosition GetGridPosition(Vector3 worldPosition)
{
return new GridPosition(
Mathf.RoundToInt(worldPosition.x / CELL_SIZE),
Mathf.RoundToInt(worldPosition.z / CELL_SIZE),
Mathf.RoundToInt(worldPosition.y / CELL_SIZE)
);
}
dunno how else to do this but i dont think this should be that bad?
Is GridPosition a class?
If you change it to a struct, like Vector3, then there will be no GC.Alloc from creating thhem.
like no jk though, a week ago these calls had no issue, what the heck did i change
its all the same
i switched from an array to a list... but... this code doesn't interact with that
Are there more of them?
yeah, im aware of structs etc , didnt think i needed to use them for this
more what sorry
More units
just 1 unit in the game with this test
@woeful leaf just skimmin a bit through here but Start was ment to be used in place of constructors. You can override the start method
Then there must be an error because it looks like you're creating 29000 objects.
yeah!! thats what i thought haha
the heck
Oh yeah I should probably just use the Start or OnEnable
would they show up in the scene hierachy **
These are just C# objects, so no
ah makes sense, what on earth have i done...
so somewhere im saying 'new' in updates or something?
What does LevelGrid.Instance.UnitMovedGridPosition do, since that's also within the profiler sample?
{
RemoveUnitAtGridPosition(fromGridPosition, unit);
AddUnitAtGridPosition(toGridPosition, unit);
OnAnyUnitMoveGridPosition?.Invoke(this,EventArgs.Empty);
}```
hmmm
GridPosition newGridPosition = LevelGrid.Instance.GetGridPosition(transform.position) this will make a new GridPosition every frame
What do these remove and add methods do?
Also, what's subscribed to the event?
public void AddUnitAtGridPosition(GridPosition gridPosition, Unit unit)
{
GridObject gridObject = gridObjects.FirstOrDefault(g => g.gridPosition == gridPosition);
if (gridObject != null)
{
gridObject.AddUnit(unit);
}
else
{
//throw excpetion?
Debug.LogError($"No GridObject at position {gridPosition}");
}
}
i think this is it... right
And remove?
public void RemoveUnitAtGridPosition(GridPosition gridPosition, Unit unit)
{
GridObject gridObject = gridObjects.FirstOrDefault(g => g.gridPosition == gridPosition);
if (gridObject != null)
{
gridObject.RemoveUnit(unit);
}
else
{
//throw excpetion?
Debug.LogError($"No GridObject at position {gridPosition}");
}
}
same thing basically
nah that can't be it these aren't called often
With this many allocations with only 1 unit, there must a loop somewhere. Does gridObjects only contain one object?
gridobject has a list of units
public GridObject(GridPosition gridPosition)
{
this.gridPosition = gridPosition;
_unitList = new List<Unit>();
}
Where do you construct it?
foreach (Cell cell in world.Cells)
{
GridPosition gridPositionOfCell = new GridPosition(cell.X, cell.Y, cell.Size.Z);
GridObject gridObject = new GridObject(gridPositionOfCell);
gridObjects.Add(gridObject);
}
in awake of levelgrid
why include Profiler.BeginSample here? Unity will sample Update on MonoBehaviours for you
i dunno, was trying to figure it out, havent used the profiler before haha
And how many cells are there?
checkin
Actually nvm. That doesn't matter much.
I'd use the memory profiler to see what takes the memory.
Can you share the whole code of GridPosition
using System;
using UnityEngine;
public struct GridPosition : IEquatable<GridPosition>
{
public bool Equals(GridPosition other)
{
return this == other;
}
public override bool Equals(object obj)
{
return obj is GridPosition other && Equals(other);
}
public override int GetHashCode()
{
return HashCode.Combine(x, z);
}
public int x;
public int z;
public int yLevel;
public GridPosition(int x, int z, int yLevel)
{
this.x = x;
this.z = z;
this.yLevel = yLevel;
}
public override string ToString()
{
return $"x: {x}; z: {z} lv: {yLevel}";
}
//BUG: this isn't checking yLevel
public static bool operator ==(GridPosition a, GridPosition b)
{
return a.x == b.x && a.z == b.z;
}
public static bool operator !=(GridPosition a, GridPosition b)
{
return !(a==b);
}
public static GridPosition operator +(GridPosition a, GridPosition b)
{
return new GridPosition(a.x + b.x, a.z + b.z, a.yLevel + b.yLevel);
}
public static GridPosition operator -(GridPosition a, GridPosition b)
{
return new GridPosition(a.x - b.x, a.z - b.z, a.yLevel - b.yLevel);
}
}
Oh, so you changed it to struct?
So is it any different now? The profiler data.
no sorry, i did this change months ago when it was working fine
trying to figure out how to install this memory analysis - got it
Well, since it's not GridPosition, it must be one of the methods here or the event(something subscribed to it to be precise).
is it possible the event is sub'd to something that doesn't show in the code?> i think ive had something like that before
Although... It's weird that the profiler is not being precise about it.
like its an old thing
No.
You can find all references in the ide.
you can use the profiling markers around specific blocks to narrow it down further
can you also remove the Profiling.BeginSample lines and check again (it's likely irrelevant, but you're actually profiling the profiling at the moment as well)
it says this block is also really bad but like...
private void HandleSelectedAction()
{
Profiler.BeginSample("HandleSelectedAction Update");
if (Input.GetMouseButton(0))
{
GridPosition mouseGridPosition = LevelGrid.Instance.GetGridPosition(MouseWorld.GetPosition());
if (selectedAction == null)
{
return;
}
if (!selectedAction.IsValidActionGridPosition(mouseGridPosition))
{
return;
}
if (!selectedUnit.TrySpendActionPointsToTakeAction(selectedAction))
{
return;
}
SetBusy();
selectedAction.TakeAction(mouseGridPosition,ClearBusy);
OnActionStarted?.Invoke(this, EventArgs.Empty);
}
Profiler.EndSample();
}
its only running when the mouse is down
the heck
invoking some event on update? i must be
BehaviourUpdate captures all classes that are using Update()
or is that when i press mouse down? and it runs that event
you've linked 3 images with different classes using Update
sorry 😦
just trying to help you identify the issue - your first post was in the update call of UnitActionSystem, but then you linked another in Unit, and this one is in EventSystem
I'm not sure if you're shifting code around/renaming it
yeah there is a few going on 😅
im not there are just a few GC allocs in a few functions
This is not Update though
private void Update()
{
if (isBusy)
{
return;
}
if (!GameManager.Instance.HasBattleStarted())
{
return;
}
if (TurnSystem.Instance.IsEnemiesTurn())
{
return;
}
if (EventSystem.current.IsPointerOverGameObject())
{
return;
}
if (TryHandleUnitSelection())
{
return;
}
HandleSelectedAction();
}
Can you remove the useless profiler samplers and enable deep profiling?
in the profiler Update() calls will show under BehaviourUpdate as {ClassName}.Update() [Invoke]
yep will do now
omg deep is working wonders
ok i know where to start looking
private PathNode GetNode(int x, int z, int yLevel)
{
GridPosition gridPosition = new GridPosition(x, z, yLevel);
return _pathNodes.FirstOrDefault(pn => pn.GetGridPosition().x == gridPosition.x &&
pn.GetGridPosition().yLevel == gridPosition.yLevel &&
pn.GetGridPosition().z == gridPosition.z);
}
That's being called every update?
no
wait what

it should run this once when i move then thats it
not continously
how many tiles do you have exactly?
im going to assume the best and say that is 20x20
yep
HEya!
What would be a good way to approach IK for legs?
My goal is to let the feet/legs/knees bend naturally, depending where the character stands.
I currently have a ray shooting down from the characters feet, and changing the collider accordingly so the feet match
If that made any sense x)
yep ive fucking found it..
Seems like it's your pathfinding system.
The allocation is probably from Linq.
im pretty sure
yeah
while the unit is moving around im constantly checking for a path
that and you should cache "GridPosition(x, z, yLevel);"
it should just it once
yeah 100% ive recently refactored a bunch and havent finished it cause i ran into this issue
var pathFound = Pathfinding.Instance.FindPath(unitGridPosition, gridObject.gridPosition, out int pathLength);
if (pathFound == null)
{
continue;
}
its this code im certain
you just linked the call stack here
https://paste.myst.rs/9lx69tzp
I ended up with this a solution by the way, I think it's decent
a powerful website for storing and sharing text and code snippets. completely free and open source.
I did not read anything about this but if you want to create a proper system for this, you might want to create a general "initialization" method that is virtual. You can then call this method and override if needed. You can also go one step further and create your own Instantiate method that will invoke this method using reflection, but this will have a hit on performance. You can look into adding source generation for this if you know how to do it.
Works too. Basically what I said, but with a method and abstract
Looks like a more complicated version of:
public abstract class MainMenuButton : MonoBehaviour
{
private Button button;
private void OnEnable()
{
button = GetComponent<Button>();
button.onClick.AddListener(OnClick);
}
private void OnDisable()
{
button.onClick.RemoveListener(OnClick);
}
protected abstract void OnClick();
}
And then the derived class just overrides OnClick
public class Quit : MainMenuButton
{
protected override void OnClick()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
Oh yeah you're totally right, I needlessly over-complicated it 😅
Thanks for the tip!
What is the best way to get correct world-space coordinates regardless of my camera angle? In this video, you can see that when the camera is top-down, it correctly displays coordinates of tiles in the tilemap. However, when I change perspective, it gets screwed up.
project ray onto plane of tilemap, use GridLayout's WorldToCell to get tile coordinates. Hard to provide any other information when you don't say how you're doing it now
Hello,
I have a 2D grid-based game with some randomly generated levels. I can spawn objects on the grid, but I want to randomly instantiate several 2x2 (grid cell) prefab objects as well, which should fit into valid patches of the cell grid (i.e. playable space, and not cut into walls).
Is there a best practice for evaluating available spaces that the object can go? I can think of many approaches to this, but my ideas all have either flaws or generate more overhead than I'd like.
For example, if I loop through the available cells, I can easily check if there's space, but then I am severely weighting the chance of instantiation towards the earlier coordinates. I want a roughly equal chance to appear at all possible positions. I could loop through and log all possible positions into a list, but that seems extremely cumbersome. I feel like there's a method I'm overlooking.
Thanks EvilReeper, that worked.
how do you find the point of where the raycastall gets out of the collider?
when you shoot a ray through a box, I'm trying to find the end point of the raycast
I guess I can't find it since ray getting out of the collider not considered a collision?
Brain twister: how the hell does this method allocate?
private static List<Box> FindBox(Piece piece) => FindSidesOfBoxOrCube(piece, FormValidTwoDimensionalBoxSide, OneSideAllowed);
Not the method it calls. THIS method.
However just in case, for completeness sake:
private static List<Box> FindSidesOfBoxOrCube(Piece piece, Func<Vector3, Vector3, Vector3, Vector3, bool> isValidSide, int numberOfSides)
{
boxes.Clear();
var boxName = 'A';
var snapNodes = piece.PrimarySnapNodes();
for (var i = 0; i < snapNodes.Count; i++)
{
for (var j = i + 1; j < snapNodes.Count; j++)
{
for (var k = j + 1; k < snapNodes.Count; k++)
{
for (var l = k + 1; l < snapNodes.Count; l++)
{
if (isValidSide.Invoke(snapNodes[i], snapNodes[j], snapNodes[k], snapNodes[l]))
{
boxes.Add(new Box(boxName++, snapNodes[i], snapNodes[j], snapNodes[k], snapNodes[l]));
}
}
}
}
}
return boxes;
}
(the boxes list as you see is not initialized but reused from the static context of the struct)
And:
private static bool FormValidTwoDimensionalBoxSide(Vector3 snapNodeA, Vector3 snapNodeB, Vector3 snapNodeC, Vector3 snapNodeD) => snapNodeA != snapNodeB && snapNodeA != snapNodeC && snapNodeB + snapNodeC - snapNodeA == snapNodeD;
That's not normal
Animation is actually a huge part of it, what are you doing with that?
Yeah
LOL
I have a frenzy spawn mode
where an enemy spawns every 0.5 seconds
and the game just dies
that big chunk was from the explosion i told ytou about
I have like simple
few frame animations
for the enemies, explosions
Having that many physics objects is going to kill your performance pretty fast.
What does it mean by physics objects
Objects with rigidbodies
o
Just my player and enemies
How do games manage large waves of enemies usually then?
Most of them aren't physics objects; they have simplified physics, if any... At least for large swarm games.
👆 That or they have special architecture, like ECS
Sometimes both
What does ECS stand for again?
Entity Component System
For example survivor.io
Ah righty
Doesn't seem too much from the gameplay videos I found online.
Should be possible with the regular workflow.
I am trying to change my post process volume values via c#, but they bounce back to the preset values...
Anyone know what I might be missing?
Yuh i think the main problem, is my explosions
If you look closely, you'll see that "other" is taking most of the time. It's probably the editor loop. Try profiling a build.
So I've never heard of that game, and they don't have their own domain which is...weird, but looking at a quick gameplay video, I'm quite confident those aren't physics objects. Imagine Robotron 2084, which ran on hardware several exponentiations worse than the dumbest smartphone, and it handled that many onscreen easily. You just simplify the AI significantly.
I know how to make an apk
Google that. It's very simple: "unity profile android build"
I'm confused as to why it doesn't exist
Its too confusing
So many steps
gamedev has many many steps
once you follow through and profile something a few times the workflow will seem easy for it
This is is what it looks like normally
because you have defined UIElement as a varaible so it stops being a type in that script
Oh wait I'm stupid it just has to be of type GameObject ofc, my bad
Yeah no it makes sense now, my bad
Okay, well, select a frame and look at the profiler hierarchy view for what's causing it.
How did it go back to profiling the editor..?😞
But either way, seems like it's something with physics.
What exactly is happening during your "explosion"?
ya u told me afte rso i unplugged me phone sry
I was moving it around
and i found this
So it might be the damage canvas
Yeah thats what i was talking about before
Say i have 20 enemies
each enemy generates a explosion
What kind of exponential function are you using?
What do they have to do with popups though?
Then how about pooling them??
Maybe i need to fix my game logic
It seems like Destruction of objects is the main issue
Ill try taking out
Does anyone who knows about Growtopia know how their world saving system works and how hard it would be to make something like that?
the damage canvas and see if it still lags
then if it still does
ill check out poolijng
So i took out the damage canvas
ANd now its just purely the physics thing
Well, why not expand it..?
You're only now going to implement that?
I was at soccer until i started debugging like 30 minutes ago
Oh okay, I was about to say that I suggested it <t:1673857620:R>
Ya, i got home started investigating this mysterious profiler relic u told me about
Yeah that's fair
Then used it find out the optimal solution to my conundrum
Is it possible to read the contents of a prefab? Like check how many buttons are contained inside a prefab?
prefabs are GameObjects like any other
they're just not active and in the scene
You can freely use the whole of the API with them
Anyone else have the same mistake
Good to know. Im making an editor script and wanted to populate a list with just the buttons of the selected prefab
Thx
Hello, im having a strange issue where if i am rotating an object and using transform.Translate() in the same frame the object starts to fly in circles sometimes.
public void Move()
{
Vector3 lookPos = anotherPos - transform.position;
Quaternion rotation = Quaternion.LookRotation(lookPos);
transform.rotation = rotation;
transform.Translate(Vector3.forward * Time.deltaTime);
}
I dont understand whats going wrong here.
Translate is relative to the object's local space, so rotating it changes the direction you translate
if you want to Translate in world space do transform.Translate(Vector3.forward * Time.deltaTime, Space.World);
well, yea, i wanna translate it forward in whatever direction i have rotated it to tho
so should i not translate in localspace?
then that's exactly what's happening
you are rotating it in a circle
so it's moving in a circle
Also lookPos is a confusingly named variable. It's not a position vector, it's a direction. Would be more clear as lookDir for example
fair enough.
But i still dont understand whats going wrong
Like, i feel like im rotating the object, thereby moving its forward vector. So then when i want to move it i should move it just forward in local space using the forward vector.
What im expecting then is for the object to just rotate towards whatever point i chose and then have it move towards that point.
No moving in circles or whatever.
Is the point you're moving towards itself moving??
no, thats a static point
Is the object you're moving towards, for example, a child of the object that this script is on?
can you show how you have set things up
i can try record a small demo, hang on
basically you have one of a couple issues most likely:
- the point you're moving towards is itself moving, resulting in constantly changing directions (e.g. if the target is a child of this object)
- You're overshooting the point and your object is then having to turn around and double back, ad nausuem
- You're overshooting the point and your object is then having to turn around and double back, ad nausuem
This could actually be it, currently my margins are 0.1f but im normalizing a vector so i should maybe simply just use 1 insted
or i mean, i was using a normalized vector, before i changed to vector3.forward but seeing as both should have a magnitude of 1 maybe my implemented guard clause to see how far i have left to the target should also have < 1 rather than < 0.1f
You could simplify this whole thing by just using MoveTowards and LookAt
I have a script for swimming, and there is a variable that changes between swimming mode and normal mode. Now, I have a if statement that says if the variable is on swim mode, the walk code is disabled.
Until now it was working fine, but suddenly it doesn't listen to the statement and swimming mode runs concurrently with normal mode. I do not know what to do. help?
ill take a look at using those insted
public void Move()
{
transform.LookAt(anotherPos);
transform.position = Vector3.MoveTowards(transform.position, anotherPos, Time.deltaTime);
}``` @candid trench
Is it possible make custom error mesages have bold text?
Or something that gives it more of an emphasis
I just realised
Using a pool would be very difficult
because i would need to pool like 500 objects...
Would it be ok to have an object pool of like 1k?
hang on, why am i not allowed to declare 2 variables with the same name here??
public void Move()
{
if (tilePath.Count() > 0)
{
transform.LookAt(tilePath[tilePath.Count() - 1].position);
if (tilePath[tilePath.Count() - 1].isOccupiedBy == null)
{
transform.position = Vector3.MoveTowards(transform.position, tilePath[tilePath.Count() - 1].position, Time.deltaTime * moveSpeed);
float distanceToNextTile = (tilePath[tilePath.Count() - 1].position - transform.position).magnitude;
float distanceToCurrentTile = (currentTile.position - transform.position).magnitude;
// Why am i not allowed to declare this twice?
// shouldnt this be going out of scope before i try to declare it again?
if (distanceToNextTile < distanceToCurrentTile)
{
currentTile.isObsticle = false;
currentTile.isOccupiedBy = null;
currentTile = tilePath[tilePath.Count() - 1];
currentTile.isObsticle = true;
currentTile.isOccupiedBy = this.gameObject;
tilePath.Remove(tilePath[tilePath.Count() - 1]);
}
return;
}
else
{
FindNewPath(tilePath[0]);
}
}
float distanceToCurrentTile = (currentTile.position - transform.position).magnitude;
//Same variable name as above.
if(distanceToCurrentTile < 1)
{
transform.position = Vector3.MoveTowards(transform.position, currentTile.position, Time.deltaTime * moveSpeed);
}
}
because a variable in an inner scope cannot have the same name as that declared in an outer scope
wut, is that a C# specific thing?
no it is a C language specific thing
really? I felt pretty confident that it's allowed in C++
hm. strange. i must be remembering it wrong then.
hello, good day to all of you. I have a problem. Its with Unity Package Manager. Whenever I start a new project there is ALWAYS A error: One or more packages could not be added to the local file system I am desperate. I reinstaled Unity 2x time but nothing. Please help
worked like a charm btw, thanks
Hello, I wrote a mod for a Unity game that has basic level of mod support ( they provide the injection for my DLL etc). Currently I have a IMGUI ui that I am looking to move to Unity's UI system. I made an Asset Bundle that has prefabs for a Canvas/buttons etc for my new UI and can load that bundle in without issue. I have also setup the scripts for the button/canvas to create the proper game objects, that I add to a root GameObject in my mod. What I'm failing to understand is how would I attach my GameObject/Canvas to the actual UI within the game so it will appear on screen? Right now setting Active "works" in that my debug log will show everything being setup as I'd expect but it isn't visible on screen
Anyone know what this error means? I looked it up on google but still have no idea what it means. I think it's probably an error in my serialization which is here:
[System.Serializable]
public class Words
{
public string word;
public string phonetic;
public string[] phonetics;
public string origin;
public string[] meanings;
public string[] definitions;
public string partOfSpeech;
}
Also, here is the API text:
[{"word":"among","phonetic":"/əˈmɒŋ/","phonetics":[{"text":"/əˈmɒŋ/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/among-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=718864","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}],"meanings":[{"partOfSpeech":"preposition","definitions":[{"definition":"Denotes a mingling or intermixing with distinct or separable objects. (See Usage Note at amidst.)","synonyms":[],"antonyms":[],"example":"How can you speak with authority about their customs when you have never lived among them?"},{"definition":"Denotes a belonging of a person or a thing to a group.","synonyms":[],"antonyms":[],"example":"He is among the few who completely understand the subject."},{"definition":"Denotes a sharing of a common feature in a group.","synonyms":[],"antonyms":[],"example":"Lactose intolerance is common among people of Asian heritage."}],"synonyms":["amid","amidst","amongst"],"antonyms":[]}],"license":{"name":"CC BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"},"sourceUrls":["https://en.wiktionary.org/wiki/among"]}]
Error is here V
phonetics is obviously not a string array
Well there is phonetic and phonetics
"phonetics":[{"text":"/əˈmɒŋ/","audio":"https://api.dictionaryapi.dev/media/pronunciations/en/among-us.mp3","sourceUrl":"https://commons.wikimedia.org/w/index.php?curid=718864","license":{"name":"BY-SA 3.0","url":"https://creativecommons.org/licenses/by-sa/3.0"}}]
I would recommend testing your approach in Unity. Create a scene that has a similar UI setup as the game you're modding (to the best of your knowledge) and use that to figure out what steps you need to take to get your Canvas to be visible
phonetics":[{"text"
phonetics is an array of objects not strings
oh ok, so should I write it as
public object[] phonetics;```
or just remove it entirely?
what you do is to learn how to define json.
Is their anything i can do to stop large amounts of collision from lagging
When running in the editor my Canvas is visible, as are the form elements. I suspect I need to set its parent within the mod? I was under the impression just activating an Instantiated canvas would trigger it to show up based on position etc
What Render Mode are you using?
ScreenSpaceOverlay
there are lots of websites where you can paste in a json string and they will generate C# classes for you. maybe you should google for one of them
Have you tested what happens if you have two Canvases active at the same time? Does it work as you expect?
You mean within the Editor?
Yes.
Is their anyway to make a large amount of collisions around 500ish not laggy?
- If this is the entirety of your JSON then it is not actually a valid JSON file. JSON must start and end with
{ ... } - You need to create a class structure that matches the structure of the JSON if you want to deserialize it.
Thanks, does this seem more reasonable?
using System.Collections.Generic;
[System.Serializable]
public class Definition
{
public string definition { get; set; }
public List<object> synonyms { get; set; }
public List<object> antonyms { get; set; }
public string example { get; set; }
}
public class License
{
public string name { get; set; }
public string url { get; set; }
}
public class Meaning
{
public string partOfSpeech { get; set; }
public List<Definition> definitions { get; set; }
public List<string> synonyms { get; set; }
public List<object> antonyms { get; set; }
}
public class Phonetic
{
public string text { get; set; }
public string audio { get; set; }
public string sourceUrl { get; set; }
public License license { get; set; }
}
public class Root
{
public string word { get; set; }
public string phonetic { get; set; }
public List<Phonetic> phonetics { get; set; }
public List<Meaning> meanings { get; set; }
public License license { get; set; }
public List<string> sourceUrls { get; set; }
}```
same error though so probably not
Unity JsonUtility cannot deserialize root array
Use actual Json serializer like Json.NET
I have the ads mediation package installed, but I can't see the settings for it
I don't think I understand what you are trying to accomplish with the test? I'm not bringing the entire video game elements into Unity editor... I'm just trying to launch my custom UI at runtime from my mod's dll - it's very easy with IMGUI, but I'm not understanding the complexity of the newer UI elements
The #1062393052863414313 won't let me post my question for some reason. Can someone help me here?
There is no support for Animation in Entities 1.0.0 yet? Current latest install via PM is 0.9.0. Are there patches/workarounds out there for this time being? I just need to import a rigged model into ECS so I can attach PhysicsJoints to its bones so I can get some physics-based animations going.
There is no support for Animation in Entities 1.0.0
I think the current way is to use companion gameobjects for animations
Ooof, any news on an ETA? Seems they went quiet again.
Pretty sure they said they'll start work after 1.0.0
So could be a year away
we just dont know
alright. thx
In DOTS/ECS, when adding a skinned mesh from a rig setup, it creates SkinMatrix buffer to the holding entity. Any way to tap into that and manipulate it's "bones" to get the mesh to deform at runtime? I'm on Entities 1.0.0 atm.
Is there any way to make table's localized string size according to it's size?
Working with large texts is PAIN
#1064581837055348857 use this channel for small questions now
hey guys, can someone help-me?
I'm building an application in unity, and I need to get a 3d object from a website.
private IEnumerator AddObjectById(int id, string name) {
string url = GlobalStateData.getInstance().ServerAdress + "bundle/ObjectBundleController/" + id;
UnityWebRequest get = UnityWebRequest.Get(url);
yield return get.SendWebRequest();
if (get.result != UnityWebRequest.Result.Success) {
Debug.Log(get.error);
yield return false;
}
else {
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(get);
GameObject obj = (GameObject)bundle.LoadAsset(name);
_place3DObjectRef.ArPrefabs.Add(obj);
yield return true;
}
}
the function always stopping in return get.SendWebRequest(), do someone know why?
horizontal = Input.GetAxis("Horizontal") * turningSpeed * Time.deltaTime;
transform.Rotate(0, horizontal, 0);
vertical = Input.GetAxis("Vertical") * Speed * Time.deltaTime;
transform.Translate(0, 0, vertical);
I have a code like this, how to limit the rotation of the cube when moving?
don't use transform.Rotate, it's additive
you'd have to track and drive the rotation yourself in a float and clamp that
I dont know what to do guys, I have read the documentation, watched videos but all this research has made me confused. My weapon snaps to the points, it doesnt move smooth to the points.
Vector3 localPos = new Vector3(0, 0, 0);
if (Input.GetKeyDown(KeyCode.Mouse1) && isEquipped == true)
{
// Move to aiming Position
transform.localPosition = Vector3.Lerp(localPos, aimPos, 1);
Camera.main.fieldOfView = 55;
aiming = true;
indicatorIcon.SetActive(false);
}
if (Input.GetKeyUp(KeyCode.Mouse1) && isEquipped == true && aiming == true)
{
//Move Back to Hold Position
transform.localPosition = Vector3.Lerp(localPos, aimPos, 0);
Camera.main.fieldOfView = 60;
aiming = false;
indicatorIcon.SetActive(true);
} ```
Do you know what Lerp does
@knotty flower Vector3.Lerp(localPos, aimPos, 1); you are lerping to the value of 1 it will always be point b in terms of from point a to point b