#archived-code-general
1 messages · Page 356 of 1
The act of unboxing does not deallocate any memory. If the object that was serving as the box is no longer referenced anywhere, it will eventually be collected by the garbage collector, like any other object.
Gotcha! Thanks.

I have a question. I have method that has an action parameter. Then inside the method, i subscribe the action with another method. Should i unsubscribe it? or just let it be since its a local variable action?
you should unsubscribe it, unless you have some place else that takes of it already, for example in OnDisable() or something
void Method (Action action) {
action += OtherMethod
}
if i do this, i have to unsubscribe it?
I'm actually not sure if delegates are pass by reference
You cannot do that as far as I know, pretty sure it is pass by value and += will do nothing.
I checked stackoverflow and you can try adding the ref keyword in front to pass in by ref, otherwise I believe invoking the action you passed in outside the method will do nothing. As in invoking action outside the method will not trigger OtherMethod
yeah, that's only reassigning the local variable action
got it thanks
What do you mean? Only a single drag should be registered, if I understand correctly? In this case, what about creating a boolean?
yeah I ended up creating a bool to flag when a drag is canceled
why is there a SceneManagement in both of the UnityEditor and UnityEngine namespaces?
Is there any reason why Image.crossFadeAlpha would work to decrease alpha but not increase it?
public void FadeOut()
{
background.CrossFadeAlpha(0, fadeOutTime, true);
text.CrossFadeAlpha(0, fadeOutTime, true);
}
public void FadeIn()
{
Debug.Log("test");
background.CrossFadeAlpha(1, fadeInTime, true);
text.CrossFadeAlpha(1, fadeInTime, true);
}
That's hardly unique to the SceneManagement namespace
Both lines run I know that for a fact
But only the Fade out method actually seems to work
Adding more logging can help diagnose the problem.
see if and when the functions are called, and what fadeOutTime and fadeInTime are set to
the function itself works fine, so your usage of it is likely wrong somehow
they are hard coded atm to 1.0f and 0.4f respectively
define "hard coded"?
Use Debug.Log to make sure the value is actually as you expect at runtime
When debugging your code it's best to question all your assumptions.
readonly variables
public readonly float fadeInTime = 1.4f;
public readonly float fadeOutTime = 1.0f;
Lemme see if the alpha values are changing via code tho
ok now add more logging to the actual functions. You don't even have a log for fadeout.
Beacuse I know fadeout works
I can see it working lol
make sure your "test" thing is even printing. It'd be better ot have an informative label there though like Debug.Log($"FadeIn called for {background} and {text}");
I think you're misunderstanding the point of debugging.
Is your log printing or not
yes
Ok but like
we still want to log fadeout
because it can give us valuable clues
for example maybe your code is calling FadeOut accidentally right after FadeIn
and that's why it doesn't appear to work
When you debug things, you need to be thorough, you can't take shortcuts
if you are thorough, you are guaranteed to find the problem instead of bashing your head against the wall
and if you put the log and it's not doing that, then at least you eliminate that possibility.
It's about playing the game of deduction
Interestingly enough. pulling the alpha in the update loop only returns 1
there's all kinds of things that could be going wrong
you could be referencing the wrong object
you could have other code overwriting the alpha
you could have an animation overwriting it
etc
public void FadeIn()
{
Debug.Log($"fading in from {background.color.a} and {text.color.a}.");
background.CrossFadeAlpha(1f, fadeInTime, true);
text.CrossFadeAlpha(1f, fadeInTime, true);
Debug.Log($"Done fading {background.color.a} and {text.color.a}.");
}
Logs the same color.a before and after
that second log isn't that helpful
crossfade takes time
it doesn't happen instantly
it won't be done on the line after
what I'm more interested in seeing is the logs when whatever happens happens that is supposed to cause the fade in. And with FadeOut having logs in it as well
basically - please provide more context here if you want more useful help.
The thing with the fadeOut method, and why I'm not concerned with it.
I instantiate the gameObject I'm fading in and out from.
And after it fades out, its destoryed.
So its not like I'm ever fading back in from fading out
Hello, does anyone know a good tutorial to create FPS Charackter controller with animation assets included weapons, I have a Asset with some animations and want now to create the movement und etc
cool, so why don't you just quickly add a log message and confirm that to be the case
and then we don't have to worry about it anymore
I did
anyone knows or have experience making procedural 2d world?
i have a lot of troubles making biome system
You want me to show you the logs of it running once?
I guess I'm confused as to what;s being asked
I want to see the damn code,
I want to understand what is going on here.
Are you aware that currently all I have seen from you is a poorly formatted 8 lines or so of code?
I have no idea what we're even trying to do here
You should ask specific questions on what you're actually struggling with. Very few people will play 20 questions to help you
I don't know anything about the project, or what these objects are, or when and why they are supposed to be fading in or out
or what script this code is on
or what code causes it to run and when
respetfully. Nevermind
i dont know how to specify where and how to put biomes, im really lost , i use perlin noise and a mintreshold and maxtreshold but look
How to Instantiate a prefab, not a clone. I want the blue link.
At runtime, there are no blue links
if you want it for an editor tool, then you use https://docs.unity3d.com/ScriptReference/PrefabUtility.InstantiatePrefab.html
you don't "specify" where to put specific biomes. It's based on the noise function
that's kind of the point
this is for procedural generation
thank you @mighty void
and exists a way to generate terrain and put biomes? i dont know, i'm a newbie
and how to specify where put that biomes?
If you want to manually place things it doesn't sound like you want procedural generation
yeah i know but i want coherency with the biomes because sometimes the biome is like 1 chunk desert 4 chunks forest, 1/2 chunk mesa, savanna never appears
adjust your noise function inputs, thresholds for the biomes, etc.
Hello! Am I right to assume that the Packages/package folder should not be included in VCS? It's 60mb heavy. I don't recall it being there before creating a Unity 6 project.
The Packages folder is meant to be included in VCS, but usually oit only includes a single manifest.json file. If you have other things in there, those are embedded packages, which unfortunately do need to be included
what do you have in there that is 60mb?
The most common reason to use an embedded package btw is if you made a manual change to a built in Unity package.
i made it but sometimes the noise always return the sames values, exist a wait to get different values bases on Xcoord? i dont know, always return 0.10 to 0.99 , i try adjusting noise with a lerp but the problem stay
Thank you so much for the quick and concise reply.
It contains a series of folders that ends in an Artifacts folder which contains very similar things to Library/Artifacts.
I have not modified anything. This is just a fresh Unity 6 project.
huh - not sure what this package folder is (the lowercase one inside the uppercase one)
I've never seen it before
I would probably try excluding it from VCS, make a basic scene, clone the repo, and see if it works on the other side
From project root it goes Packages\package\ProjectData~\Library\Artifacts
"ProjectData~" is the only thing contained inside "package".
Here's a sample of what's contained.
I would definitely exclude at least the ProjectData~ folder if not the entire "package" folder (keep Packages)
I'll give that a try when I get to it, thanks!
It does feel like it would be regenerated. I'll delete it and restart to see what happens.
basically... the stuff you're seeing there is like... some normal contents of the Library folder
and we always exclude the Library folder
it's very confusing to me that it's showing up inside your Packages folder 🤔
Yeah I found an identital folder with a different amout of such subfolders and files under Library which has me confused.
I do wonder if it's a Unity 6 bug or something
Same here.
I wouldn't be surprised!
It doesn't seem to get generated again. Not when restarting nor when pressing play.
any chance it got copied in there accidentally somehow?
If you make another new project do you see it again?
has anyone ever had the unity editor fail to open any project at all. I have a guy and we set up him with unity- has a personal license. create a new project or try and open an existing and the editor will simply fail to open. tried running the hub with admin and all sorts but nothing
it wont even start up
Definitely not, this project is fresh out of creation.
I'll try that.
The project is still generating and the folder is already there.
So for enemies in encounters, would I be better off storing their stat values in scripts attached to their prefabs?
Or would it be better to have them all stored collectively in a script as a list
That package folder is from the project template in the hub (the provided ones have it), but it's not supposed to be sticking around as it pulls the stuff out of there to make your project 
Consider looking into ScriptableObjects and assigning these to Prefabs.
I already have a scriptable object for the base stats of enemies
I mean in active combat where should I store stats
for example
I cant just pull directly from the SO, because a fight could have 3 "soldier" units for instnace
and doing that would make them share hp
Oh, so it's a remnant from the generation of the base template project?
Yeah, not sure why it's still there for you
I would assume this is a Unity 6 preview bug. I've literally just installed Unity on this PC and created a project. I'd be surprised to have broken something somehow.
Thank you both for your help! I'll just delete it and be happy! 
Im thinking I could maybe just have an "enemyStat" script applied to every enemy prefab, which uses its ID component to get its stats
Consider using ScriptableObjects for initialization rather than for runtime stat updates.
Thats what Im doing
Having the enemyStat script on startup take the enemyID from its own object and pulling the needed stats from the SO
I still need runtime stat updates for the sake of damage, status effects and other changes
My looking around / movement feels very jittery. What might be the problem?
Here's my looking code
https://hastebin.com/share/ukiximosaz.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Here's my movement code
https://hastebin.com/share/ewoqehaqip.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is your camera a child of your rigidbody
(I'll just drop this here since I've had this saved in my bookmarks forever)
The solution was to set the alpha of the canvas renderer to anything non-zero before using CrossFadeAlpha.
Hey can anyone help me, I'm not sure why but when I grapple I get launched into oblivion? I'm not sure why and I'm sure it's from this script, especially the getkeydown function part.
!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.
Try configuring the damper?
Did you remember to set the values in the inspector
Lmao dumbest idea ever what if I just automatically set the physics tick rate to Time.deltaTime
i tried to create rotate around player ```using UnityEngine;
using Unity.Cinemachine;
public class CameraController : MonoBehaviour
{
public CinemachineFreeLook freeLookCamera;
void Update()
{
if (Input.GetMouseButton(1)) // Right mouse button
{
// Enable camera rotation
freeLookCamera.m_XAxis.m_MaxSpeed = 300;
freeLookCamera.m_YAxis.m_MaxSpeed = 2;
}
else
{
// Disable camera rotation
freeLookCamera.m_XAxis.m_MaxSpeed = 0;
freeLookCamera.m_YAxis.m_MaxSpeed = 0;
}
}
}
but this library deprecated
So only sorta a code question. I was following a Unity folder structure video to get an idea of good practices and am running into a issue.
I have a ScriptableObject called ScriptableUnitBase snippet here:
public abstract class ScriptableUnitBase : ScriptableObject
{
public Faction Faction;
[SerializeField] private Stats _stats;
public Stats BaseStats => _stats;
// Used in game
public FriendlyUnitBase Prefab;
// Used in menus
public string Description;
public Sprite MenuSprite;
}```
Which is inherited by ScriptableFriendly which is the object i create in my project: `public class ScriptableFriendly : ScriptableUnitBase`
Now I am trying to assign my Player prefab object, which has a Player script to the scriptable object instance.
Player inherits from FriendlyUnitBase: `public class Player : FriendlyUnitBase` which inherits from UnitBase `public abstract class FriendlyUnitBase : UnitBase`.
The issue I am having is that the FriendlyUnitBase Prefab variable will NOT allow assignment of the Player object. I even tried setting the variable to take Player object, etc but nothing would allow me to assing a prefab to that variable.
What I am i missing?
oh
Is there a way to store strings outside of the globalmetadata.dat file?
I have a bunch of strings in which I need to keep secret as they contain links to game servers
Is there perhaps a package for this I can install?
if someone could help me
it worked, kind of, but thanks!
i don't know it makes you fall through the floor still and like you don't swing around at all there's nothing keeping you up (pulling you up), like no centripetal force whatsoever
Hey,
I wrote a script for my prefab.
Created 500 game object with different positions. (Clones)
How to link them back to blue link prefab? I have to more modifications and don't want to make.them manually for each
Then lower the damper and up the spring
If you spawned them in the editor, changing something on the prefab will apply to all instances of it as long as that field isn't already changed
link them back to blue ?
drawing arrows on a tilemap
private void GenerateTwistedTorusWithoutNormalVector()
{
vertices = new Vector3[thetaDivisions * phiDivisions];
rotations = new Vector3[thetaDivisions * phiDivisions];
float minorRingTwistIncrement = _offsetAlignment.y;
for (int i = 0; i < thetaDivisions; i++)
{
float phi = 2.0f * Mathf.PI * i / thetaDivisions;
for (int j = 0; j < phiDivisions; j++)
{
float theta = 2.0f * Mathf.PI * j / phiDivisions;
float majorRadiusTwist = _offsetAlignment.x * j / phiDivisions;
float twistedTheta = theta + minorRingTwistIncrement;
float x = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Cos(phi + majorRadiusTwist);
float y = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Sin(phi + majorRadiusTwist);
float z = minorRadius * Mathf.Sin(twistedTheta);
Vector3 position = new Vector3(x, y, z);
vertices[i * phiDivisions + j] = position;
//rotations[i * phiDivisions + j] = GetLookVector(position, theta, phi); // fail code
}
}
}```
How do I get a pointing vector that points from a position to a distation in this use case? I can't get a vector to just point from A to B correctly because I am struggling to comprehend my own torus math no matter how hard I try to simplify it.
I am not good at vectors, worse at rotations and directions and quaternions. I just want to say 'From any given point, give me the direction to point at your center'
The center of a given ring's minor radius
I can set all the positions correctly perfectly, but Ive failed for hours to correctly then point at their root
Use built in quaternion methods, like LookRotation
I have been, it produces nothing but failure after failure. Quaternion.LookAt never returns correct values
I stopped trying to use quaternion.Anything because they are a black box of which I have no comprehension why its going wrong because I cannot get any debug info out of them
likewise when I say 'Vector3.foward' or whatever, that just causes more issues because what IS forward?
Then you should share your issues with that. Doing your own trig imo is rarely needed. I've yet to use any trig function in my game
Sure, 1 sec I keep deleting the code that doesnt work
Look at the docs, this is just 0,0,1.
Right sorry I didn't mean literally what is vector3 forward, you aren't understanding
Ill try to speak more clearly
I am asking in the insane exasperated way that 'vector3 forward', forward as a concept is meaningless without 3d space around it, what is 'forward' on any given point is equally meaningless
like in space there is no down
so when the net is like 'just point it forward'
it doesnt help
because nothing.forward has produced
Can I keep it a child of my rigidbody if I manually set the position every frame in late update
Anyways sorry the code, focusing on the code
I appreciate your patience in advance, I have been grinding mybones to bloody tears spending h ours making only backwards progress just trying to get to point from A to B
What do you mean. A vector3 is in 3d space. It simply points in world space (0,0,1) and that's all
Nevermind I see you're only interested in arguing about semantics with me :/
I really dont need this
I am trying to be helpful and civil, I don't appreciate the ongoing friction
You can't say you're bad at vectors then say someone's simply arguing semantics. Forward us literally 0,0,1 in world space.
It will always point along the z global axis regardless of where you are.
private void GenerateTwistedTorusWithoutNormalVector()
{
vertices = new Vector3[thetaDivisions * phiDivisions];
rotations = new Vector3[thetaDivisions * phiDivisions];
float minorRingTwistIncrement = _offsetAlignment.y;
for (int i = 0; i < thetaDivisions; i++)
{
float phi = 2.0f * Mathf.PI * i / thetaDivisions;
for (int j = 0; j < phiDivisions; j++)
{
float theta = 2.0f * Mathf.PI * j / phiDivisions;
float majorRadiusTwist = _offsetAlignment.x * j / phiDivisions;
float twistedTheta = theta + minorRingTwistIncrement;
float x = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Cos(phi + majorRadiusTwist);
float y = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Sin(phi + majorRadiusTwist);
float z = minorRadius * Mathf.Sin(twistedTheta);
Vector3 position = new Vector3(x, y, z);
vertices[i * phiDivisions + j] = position;
//rotations[i * phiDivisions + j] = GetLookVector(position, theta, phi); // fail code
}
}
// Apply the calculated positions to clones
for (int i = 0; i < clones.Length; i++)
{
clones[i].transform.localPosition = vertices[i];
}
}```
What I want from this code is to set every position's rotation to face towards the center of its minor radius centerpoint
the minor radius center point is the position on the major radius which the minor radius is arrayed around
I can say all of that in english words, nothing I type in code has achieved that result
I've got an issue I don't quite understand and haven't seen before. I have a wheel that when I rotate using the rotation gizmo rotates correctly at it's center pivot point (the way a wheel should rotate) but when I rotate it using the X value of the rotation in editor (and code) it rotates along a pivot point that is completely different. Any ideas?
🤷♂️ if you ask what Vector3.forward is, then expect an exact answer on it. Nothing about it was even semantics. You're simply confused on what a vector is
For starters make sure that it's the same object.
I'm not and I don't appreciate everyone dogpiling to attack me, I'm just going to leave because no one is interested in seeing my point of view, you'd all rather argue semantics than to help
Thank you for your time
It is
If I rotate with the gizmo tool it rotates on the axle
If i rotate with the x value of the transform is rotates along a pivot point to the left
Share the code them
You have the gizmos in "center" mode. That would rotate the object around its center. While everything else would rotate it relative to it's pivot point. I guess that's the issue.
I changed that same thing
Also, at this point it's not even a coding question. #💻┃unity-talk
May I ask what you are doing this for?
A vector from point a to b is just b - a
You can normalize it to have length 1 if you want
(b-a)/||b-a||
Just rotating towards the center of a Taurus it looks like. Not sure why the took the direct and helpful answers as "semantics" but that is kinda standard for them
is this what you mean by a twisted torus?
Does anyone have a list of commonly used lines of code
There's the C# documentation and reference... If you mean like common architectural solutions, there are nice resources on "design patterns" out there.
If you're looking for foundational knowledge of the language and syntax, you might work through the Microsoft lessons
If you mean something else, you might need to elaborate 😅
Does IL2CPP AoT have strictly superior performance compared to JiT mono? I've read that it reduces overhead during startup of the game, but haven't found much concrete information beyond this
It would depend a lot on the platform, the environment and the project. It's supposed to be faster, but there's no definite answer. The best you can do is test and profile and see for yourself.
Is there any way I could make it so that a UI behind another UI cannot be interacted with if the mouse is over the front UI?
I've used a big ol' transparent panel for that purpose, in the past
what do you use now?
I'm using an asset to render (P)React to UI Toolkit 🙃
I have yet to dig into layering separate UIs though
But coming from a web background, absolutely in love with the workflow
Thanks that's what I needed
heya, I have a camera rendering question
I'm making a game that uses pixel-perfect outlines all over the place. that works great, but my problem is that I want to be able to shift the camera" closer" to the player without increasing the size of the pixels. orthographic size, unfortunately, does what I want in terms of zooming in, but it also makes pixels proportionally larger
is the only way to solve this issue rendering to a render texture, scaling it up, and displaying it to the screen?
I ask mainly because it seems super inefficient to "record" twice as much map as is actually shown to the screen
!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.
yeah sorry idk why tf i thought you could help without the code
yes it's the child of a rigidbody but setting the position manually should help override that right
where is movement script
do you know what the issue might be
there is a lot gooing on in the movement script lol make sure you debug the direction values
im guessing at some point you're applying forward vel to something that might be rotating on the pitch
make sure this is being applied also to correct object yea
transform.localEulerAngles = new Vector3(xRotation, 0, 0);
or maybe one of the projected vectors
wdym by rotating on the pitch
like the pitch axis?
if so, then i’m not
the only thing i’m adding force to is the player rigidbody which has its axes locked except for yaw
its on the correct object to be sure
you checked in the inspector as well what is the values of player ?
is it just happen when you move / look at same time?
which values?
yes
rotation, make sure its what you expect it
the rotation is what i expect it to be, yes
can i put multiple materials in a mesh renderer like this and then choose a material dynamically?
or is it gonna try and render all the materials at once
pretty sure you can, yeah
but there’s a better way
just store it in a list or array
like in a public variable in a script?
private, serialized variable
[SerializeField] private List<Material> objectMaterials = new List<Material>();
I think
Roughly that
will that show up in the inspector or do i need to like load the asset somehow?
it shows up in the inspector and can be assigned like a public variable. that’s what serializefield does, it’s really helpful
Lmk if you would like for me to stop pinging you but I’m still really stuck on this :(
If every spawning object made using prefab. Then in what case we should make a new class and constructor?
These 2 things are totally unrelated to each other. Maybe clarify what you mean? Or provide some examples?
Have you ever used a prefab in scene? What color is it
When importing "Starter Assets character controller" getting error StarterAssetInputs could not be found.
Please help!!
Sounds like a script did not transfer with the rest of the controller. You can try reimporting it or trying to see where they got that controller from or making it yourself.
In an empty project, importing it doesn't give any error.
I need to look into my project once.
Thank you!!
That's great. Sometimes putting assets into an empty project and moving it over is the best answer.
This assigns the "Type Mismatch" in the editor for some reason:
thumbnailTexture = AssetPreview.GetMiniThumbnail(prefab);
thumbnailData = thumbnailTexture.GetRawTextureData();
thumbnailWidth = thumbnailTexture.width;
thumbnailHeight = thumbnailTexture.height;
thumbnailPreview = Sprite.Create(thumbnailTexture, new Rect(0, 0, thumbnailWidth, thumbnailHeight), Vector2.zero);
It feels like it shouldn't? The thumbnailPreview becomes what seems to be a valid sprite when I step through breakpoints.
But it becomes "Type Mismatch" instead.
Might want to provide some more context and the actual error details.
I'm trying to make a Sprite out of a Texture2D. And when I run the code above, this happens:
Type mismatch
And I am not sure why
What type is ThumbnailPreview?
Sprite
Can you share the !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 already did?
The whole script I mean
Due to this being work, no. I can't.
I can share snippets.
But even if I shared the rest of the script, it won't change anything. The code snippet I sent is the whole thing.
I want to call the method and generate a sprite from the resulting Texture2D. That's it.
Share the top of the script down to the serialized field in question then.
What is it you are looking for?
The actual type you're using for the field. There's a chance that it's a type from a different namespace for example.
[SerializeField] private Texture2D thumbnailTexture;
[SerializeField] private Sprite thumbnailPreview;
using System;
using UnityEditor;
using UnityEngine;
Is that all?
Yep
Okay🤔
I'm just as confused as to why it doesn't work.
Are you using a custom inspector/editor perhaps?
Hmm, I'm using a package to create the button that I press to generate the thumbnail in the editor.
This one https://assetstore.unity.com/packages/tools/utilities/inspector-button-pro-editor-buttons-with-parameters-151474
if you are making the sprite from the texture why is the Sprite even serialized?
It's just to preview the sprite in the editor
I could do with the texture but couldn't think of a way to use the texture in a scriptableobject to achieve that
So I thought maybe I could use a sprite instead
so show the inspector of the texture
It might or might not be that. Can you try disabling it?
Does not seem to be the culprit.
youve dropped a texture iinto the texture field, show the inspector of that texture asset
I don't understand what that means.
How can I do that? Do you want me to write an editor script for that or?
just select the texture asset in the project view and screenshot it's inspector
But it's not a texture asset. It's generated by using the Asset Preview AssetPreview.GetMiniThumbnail(prefab);
this is an asset is it not?
In my asset folder? No.
well there you go, you are trying to make a sprite from something that cannot be converted to a sprite
Btw, does the issue persist if you use a debug mode inspector?
It's a Texture2D?
Why can it not?
It's a Texture2D that Unity itself generated.
And if that was the problem, they'd just get a null reference instead
there are many flavours of Texture2D
It would've been a valid point, if you were getting a null instead.
That's what I'm thinking too
Can you take a screenshot with a debug inspector?
Is there a way to listen to the OnDrag event of a scrollrect from the outside?
Hmmm. Weird indeed. What do you see in the debugger?
Well given the data that's put in the thumbnail data array, it appears that a texture is made.
But it just won't create a Sprite from it 🤷♂️
Or, well, it does
But it's seen as a Type mismatch
cullinggroup currentDistance is always 0. How can I get this to work?
Hi! I have a question: is it normal practice to organize files into folders in a project? I find it convenient because I can access any class or dependency from anywhere in the application. I’m not sure how others generally do it. Should I expand this organization? UI/SCENE
Hi guys, how u doing ?
I'm using Synty Characters for my game. As i use mixamo animations, i need to use avatar to make my animations work. Nevertheless, i'm also using animation rigging package to make my own animations. But, now, as i use an avatar on my animator, i can't reference my rig anymore. Does anyone have a solution?
not a code question. #🏃┃animation
sorry
hey all, not sure where the right place to ask this is. I'm in love with the appearance of GLLines in game, and I think they are terrific to convey info to the player. My issue is that they are cumbersome to work with. Does anyone know if any assets or git repos for a GLLinesManager class of some kind that doesn't suck(has minimal impact on performance)? Ideally I'd use it to draw just some basic lines and circles
Hello everyone, i was trying to use unitys webcamtexture on visionos to get the persona, but for some reason, the material stays white. The problem I have right now is this docs page: https://docs.unity3d.com/Packages/com.unity.polyspatial.visionos@1.2/manual/WebCamTextures.html
MarkDirty does not take webcamtextures as a type, so I tried to copy the texture from the webcam to a rendertexture and update that, but i guess, that does not do the trick of updating the webcamtexture still.
Graphics.CopyTexture(texture, renderTexture);
PolySpatialObjectUtils.MarkDirty(renderTexture);
Well, nevermind, I jsut found out, its broken 😄 https://discussions.unity.com/t/does-unity-for-visionos-support-personas/366183/7 gonna wait for .41 then I guess
This is interesting, thank you
https://assetstore.unity.com/packages/tools/gui/aline-162772 https://arongranberg.com/aline/features There is ALINE for in-game / editor high performance gizmo drawing, however it does have antialiased lines. Not sure what specifically is appealing about GL lines to you, but if it's their aliased nature then you might just have to set up your own GL drawer. ALINE also costs money, but you could look into the features and see if it's interesting to you.
I personally use it for debugging tools but I can imagine it could be used for in-game UI with the right art style
Transform have unexpected behaviour regarding passing it as "in" parameter:
since Transform is Reference type it only should disallow to reassign new value to it. so expected behaviour in general is: ```C#
var my = new MyClass();
void ChangeMyObject(in MyClass myObject)
{
myObject.Value = 3;
}
Console.WriteLine(my.Value); // 0
ChangeMyObject(my);
Console.WriteLine(my.Value); // 3
class MyClass
{
public int Value { get; set; }
}ButC#
public void OnUpdate(in Transform cursorTransform)
{
cursorTransform.position = transform.position;
}``` do not change position of object :/
- before any one ask: OnUpdate is called properly in some other place that I omitted here I double checked it with some Debug.Log
I doubt this problem has anything to do with in parameter
likely your obejct has a CharacterController or an animator or something
are you talking about a Prefab ?
In playmode prefabs don't exist, they are just regular gameobjects
that being said, there's no reason to pass Transform as an in param.
its just a squere with my one script
private void GenerateTwistedTorusWithoutNormalVector()
{
for (int i = 0; i < thetaDivisions; i++)
{
float phi = 2.0f * Mathf.PI * i / thetaDivisions;
thetaCenters[i] = new Vector3(majorRadius * Mathf.Cos(phi), majorRadius * Mathf.Sin(phi), 0f);
for (int j = 0; j < phiDivisions; j++)
{
float theta = 2.0f * Mathf.PI * j / phiDivisions;
float majorRadiusTwist = _offsetAlignment.x * j / phiDivisions;
float twistedTheta = theta + minorRingTwistIncrement;
float x = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Cos(phi + majorRadiusTwist);
float y = (majorRadius + minorRadius * Mathf.Cos(twistedTheta)) * Mathf.Sin(phi + majorRadiusTwist);
float z = minorRadius * Mathf.Sin(twistedTheta);
Vector3 position = new Vector3(x, y, z);
Vector3 direction = (thetaCenters[i] - position).normalized;
Quaternion rotationQuaternion = Quaternion.LookRotation(direction);
vertices[i * phiDivisions + j] = position;
rotations[i * phiDivisions + j] = direction;
rotationQuaternions[i * phiDivisions + j] = rotationQuaternion;
Debug.DrawRay(position + transform.position, direction, Color.red);
}
}
}```
Quaternion rotationQuaternion = Quaternion.LookRotation(direction); is giving me the wrong euler rotation but I am not experienced with quaternions enough to know why its wrong or how to adjust it to fix it. Pictured is how its wrong, expected is they all point towards the center but together on the same axial plane
How do I adjust / replace:
With something that will correctly LookRotation at my point without twisting the rotation weirdly?
I am guessing what it needs is an Up vector, but I am uncertain how to determine what that value should be
you'll want to provide the second parameter to LookRotation as well
Would the Up be relative to.. something?
I am guessing its up 'around' the major radius? But what is that as a vector
it's a little unclear from the picture here exactly what you want but you'd probably want something like the normal of the "ecliptic plane" of each circle if you get what I mean
yeah this
probably you can take the cross product of the direction from the center to the center of the little circle and world forward
or like "big circle forward"?
e.g.
Vector3.Cross(thetaCenters[i], Vector3.forward)``` maybe?
the terms I am using are major radius and minor raidus to refer to major being from the center point of all of it to the torus outer ring, and minor being around that ring 🤔
Ill try that
it will break if the "major" circle needs to rotate though
nice
Worked like you said, until rotated
That's still better than what I had when I started
reticulate my splines
or you could just child them to the center and rotate the center
Im doing a ton more rotations and positions after this so the childing thing wouldn;t work here, so I will look into calculating theta cross per child instead of per thetan
Biblically accurate angel
some of the movements when its not a cubes (which don't cirrently orient due to the above code missing that we're working on)
I changed the math to use world for everything in world space and then transformed to local space only after so that rotation was still correct
2/3 axises now behaving as desired
the last axis to fix is the twist shown here, each one still targets its original theta ring center point, but I have to recalculate the theta ring center point as an offset around the theta on an individual basis 🤔
nice
😮
all three axis working now.
https://pastecode.io/s/jbtg4hsb
code's too big to post so here is a link
My game works fine 0 error in the editor, but when I build the game, I get an "object reference not set to an instance of an object" error. This error does not occur in the editor, only when I play the game in the build. The code where this error occurs is as follows: void Update()
{
if (playerHealthbar.isDead == false && Time.timeScale != 0f)
{
if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))
{
// anim.SetBool("isAttacking", true);
meleeStateMachine.SetNextState(new GroundEntryState());
}
}
} ( if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState)) this part is the error i get )
firs thting to do is look at the line number and filename indicated in the error
Also !code for posting code 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.
i mention that ( if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState)) this part is the error i get ) here
oh sorry
📃 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.
!code cs if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))
📃 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.
read the bot thing
it's explaining hjow to format your 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.
oh sorry lol
wait im reading sorry 🙂
cs if (spellCaster.Casted == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))
here is part where i get error
Ok it's a basic NRE
so either:
spellCaster
meleeStateMachine
or
meleeStateMachine.CurrentState are null
use logs or the debugger to find out which, and resolve it
And yes I understand this is only happening in your build. That doesn't change anything
like what ? i added debugs and i did get nothing
It's probably happening in the build only due to script execution order issues
wdym you "did get nothing"
wait let me try it again
you're supposed to read the log output to determine which thing is null
So ive tried this multiple ways and I am unsure of where the issue is. I have a scriptableobject that has the following variables (tried two ways)
Attempt 1:
[HideInInspector]
public BaseAnimationController baseAnimationController { get; protected set; }
Attempt 2:
protected BaseAnimationController _baseAnimationController;
public BaseAnimationController baseAnimationController => _baseAnimationController;
Both result in it still being shown in the inspector which I don't want as it's programmatically assigned
First thing's first:
- Do you have any compile errors in the console?
Second thing second:
- Does this thing have a custom editor?
properties are not shown in the inspector unless they have the [field:SerializeField] attribute
You are a true savant. A compiler error (hidden from easy view by an "inaccessible code" warning") was preventing the reload and I didnt notice.
{
if (playerHealthbar == null)
Debug.LogError("playerHealthbar is not assigned.");
if (spellCaster == null)
Debug.LogError("spellCaster is not assigned.");
if (playerMovement == null)
Debug.LogError("playerMovement is not assigned.");
if (meleeStateMachine == null)
Debug.LogError("meleeStateMachine is not assigned.");
}``` i added this debugs and none of them are null...
not null at start
why are you checking in start
you need to check right before the error happens
You're also not checking meleeStateMachine.CurrentState
which is one of the things that could be null
okey sorry for that let me check again
oh now i get message bc of the meleeStateMachine.CurrentState is null when i try it on build
I don't understand why I'm getting the error even though the StateMachine is a public variable and I assign it manually. Could the issue be due to the StateMachine code?
show your full code
CurrentState presumably starts null
and hasn't been set by the time you try to access it
that is the problem
using UnityEngine;
public class ComboCharacter : MonoBehaviour
{
public SpellCaster spellCaster;
public PlayerMovement playerMovement;
public DamageSword damageSword;
public PlayerHealthbar playerHealthbar;
public Animator anim;
public StateMachine meleeStateMachine;
public Collider2D hitbox;
// [SerializeField] public GameObject Hiteffect;
void Update()
{
if (playerHealthbar == null)
Debug.LogError("playerHealthbar is not assigned.");
if (spellCaster == null)
Debug.LogError("spellCaster is not assigned.");
if (playerMovement == null)
Debug.LogError("playerMovement is not assigned.");
if (meleeStateMachine == null)
Debug.LogError("meleeStateMachine is not assigned.");
if (meleeStateMachine.CurrentState == null)
Debug.LogError("meleeStateMachine.CurrentState is null");
if (playerHealthbar.isDead == false && Time.timeScale != 0f)
{
if (spellCaster.Casted == false && playerMovement.isPlayerInteractsWithNpc == false && Input.GetMouseButtonDown(0) && meleeStateMachine.CurrentState.GetType() == typeof(IdleCombatState))
{
// anim.SetBool("isAttacking", true);
meleeStateMachine.SetNextState(new GroundEntryState());
}
}
}
public void Attack2True()
{
damageSword.Attack2 = true;
damageSword.Attack1 = false;
damageSword.Attack3 = false;
}
public void Attack3True()
{
damageSword.Attack2 = false;
damageSword.Attack1 = false;
damageSword.Attack3 = true;
}
public void Attack1True()
{
damageSword.Attack2 = false;
damageSword.Attack1 = true;
damageSword.Attack3 = false;
}
public void FinishAttack()
{
anim.SetBool("isAttacking", false);
}
public void StartAttack()
{
anim.SetBool("isAttacking", true);
}
}
!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.
do you want to see the stateMachine script also ?
only if you post it correctly
yes
public class StateMachine : MonoBehaviour
{
public string customName;
private State mainStateType;
public State CurrentState { get; private set; }
private State nextState;
// Update is called once per frame
void Update()
{
if (nextState != null)
{
SetState(nextState);
}
if (CurrentState != null)
CurrentState.OnUpdate();
}
private void SetState(State _newState)
{
nextState = null;
if (CurrentState != null)
{
CurrentState.OnExit();
}
CurrentState = _newState;
CurrentState.OnEnter(this);
}
public void SetNextState(State _newState)
{
if (_newState != null)
{
nextState = _newState;
}
}
private void LateUpdate()
{
if (CurrentState != null)
CurrentState.OnLateUpdate();
}
private void FixedUpdate()
{
if (CurrentState != null)
CurrentState.OnFixedUpdate();
}
public void SetNextStateToMain()
{
nextState = mainStateType;
}
private void Awake()
{
SetNextStateToMain();
}
private void OnValidate()
{
if (mainStateType == null)
{
if (customName == "Combat")
{
mainStateType = new IdleCombatState();
}
}
}
}
ok it's pretty clear
you're not setting CurrentState until the first Update is called for StateMachine
hey guys
Simply, ComboCharacter's Update is running before the one on StateMachine, hence CurrentState is not yet set @unborn oracle
oh then what should i do to fix that
when i try to export my game it gives me compiler errors
you could also just do this whole part:
if (nextState != null)
{
SetState(nextState);
}```
In the getter for CurrentState instead of in Update
Read the errors one by one and fix them
care to share them or are we just supposed to guess
When sharing code that long, please do so properly as shown by the bot in the "large code blocks" section.
Formatting is for just a few lines
Sorry, I'm a bit of a beginner, so I didn't understand exactly what I need to change and fix. i understand the problem but i dont know what to do
Right now you're doing this "SetNExtStateToMain thing in Awake
which is... weird
why don't you just directly set the state to the starting state there?
e.g.
SetState(mainStateType);```
the whole "nextState" system you have is kind of weird
your state machine should never not be in any state
Thank you soo much now i fix it thanks to you ❤️
Hey everyone I Have an optimization pb. I'm making a turn based game and in my battle manager I have a coroutine that manage the battle.
It looks like this
private IEnumerator Turn()
{
yield return new WaitUntil(LoopCanStart);
InitialiseBattle();
while (true)
{
StartTurn();
playerInstance.StartTurn();
_playerTurn = true;
Debug.Log("Before WaitPlayer turn");
yield return new WaitWhile(()=>_playerTurn );
"End Of Player Turn".ColorDebugLog(Color.black);
playerInstance.EndTurn();
opponentInstance.StartTurn();
OpponentTurn();
yield return new WaitWhile(() => _opponentTurn );
opponentInstance.EndTurn();
yield return new WaitForEndOfFrame();
}
}
the thing is each time I press the button that make _playerTurn true the coroutine take more and more time to load up to 1/2 min at the end and I have no Idea why.
The function called are very simple (variable check and little value change)
Does someone have any idea ?
Thanks in advance !
(picture of the profiler in my next msg)
getting the weirdest thing rn
trying to increment a float that's part of a struct, and its quite simply just not
however, the rest of the code is executing, because it snaps the position of this object back to where the struct's data says it should be
What is the context ? struct are not serialized object so if you try to increment it by ref or something like that it will not do anything
oh, right
Can you share your code maybe ?
looks like you're allocating 3.45 GB of garbage
I've just changed it to a class
im coding tracers for bullets. every fixed update, it should move the tracer along the path between a start and end point. I think using structs may have been my mistake
Yup but I dont know where it's from or how I can change it
Sounds like you're misunderstanding how value types work
show your code?
public class Tracer
{
public Transform tracer;
public float t;
public float distance;
public Vector3 start, end;
public float increment;
}
the struct
sorry, i changed it a moment ago
until about 2 minutes ago, it was a struct.
the code for lerping the tracer between start and end
tracers.ForEach(x =>
{
if (x.tracer != null)
{
x.tracer.position = Vector3.Lerp(x.start, x.end, x.t);
}
x.t += x.increment * Time.fixedDeltaTime;
});
yeah this isn't going to work with structs
you can't do Foreach
you need a regular for loop
and then you would:
- copy the struct out of the list/array
- modify it
- write it back into the list/array
e.g.
for (int i = 0; i < tracers.Count; i++) {
Tracer tracer = tracers[i];
tracer.something = something;
tracers[i] = tracer;
}```
otherwise you're just modifying your local variable
now that its a class, it works just fine
sure but it will be less efficient
but yeah you are missing the fundamental understanding here of the difference between classes and structs
i.e. how value types work vs reference types
Never really though about this before but for scriptable objects but should you encapsulate scriptable object properties or just make them public?

🤣
Whenever I write public, I almost always make it a property.
Ok so I'm trying to reduce the GC in the coroutine but Can't find a way to store a WaitWhile inside a var does someone have an idea ?
I find it useful to think about properties as any other variables or methods.
If you need a property, which can be accessed outside of the class, make it public, otherwise, it can stay private. For example, when you have a WorldMousePosition property in your Player class, which returns the converted Input.mousePosition using the main Camera. Surely, it can be a method, but it does not matter if there is no parameter required.
It makes sense to still start a property from the capital letter, regardless of its access modifier, and make sure you also create a variable, assigned to the required property, to reduce the performance as much as possible, as you would've done it using a method
How are you attempting to? They can be referenced from a variable just fine
Okay, so lets say I have a variable called "characterName" in my character scriptable object.
No other scripts will change this variable.
I could encapsulate it as so:
private string characterName = string.empty;
public string CharacterName => characterName;
or just do it like this:
public string characterName = string.empty;
Right now I'm trying something else
while (true)
{
StartTurn();
playerInstance.StartTurn();
_playerTurn = true;
Debug.Log("Before WaitPlayer turn");
while(!_playerTurn)
{
yield return _waitForEndOfFrame;
}
"End Of Player Turn".ColorDebugLog(Color.black);
playerInstance.EndTurn();
opponentInstance.StartTurn();
OpponentTurn();
while (!_opponentTurn)
{
yield return _waitForEndOfFrame;
}
opponentInstance.EndTurn();
yield return new WaitForEndOfFrame();
}
And i stored _waitForEndOfFrame
Why are you creating the variable INSIDE of the coroutine?
This is spesifically for scriptable objects. Not in genral
That is fine... What makes you think it doesn't work?
I don't see a reason that should make any difference.
No other scripts will change this variable? You also don't have a setter for it, so it would make sense to make it readonly if it's only assigned once.
private readonly string _characterName = string.Empty;
I Think it's best to encapsulate so you can't change the content of your scriptable in game by accident
It doesn't not matter. There is no difference, whether it's for ScriptableObjects or not
The coroutine never pass the waituntil
I thought you couldn't serialize readonly variables. No?
Because I can't assigne New WaitUntil(_playerTurn) outside of a function, but I could do it in the start before launching the coroutine
Right, you cannot. Don't make it readonly if you need to serialize it. Note that you are also not able to serialize properties unless it's without a setter and you're using the [field: SerializeField] attribute
Like it's not proceeding past yield return playerTurnWait; (and you're feeding Turn() into StartCoroutine(), just to be absolutely sure?)
Well yeah, not outside a function. But you can make it a class member, and as you said assign it ONCE in something like Awake or Start
Instead of over and over when calling Turn and only storing it locally and then throwing it away
Oh I thought you just couldn't serialise properties (within unity) at all.
[field: SerializeField]
Oh. Missed that that was said already
Yup
Tru tru I dit it like this just to test if the storing method worked but it doesn't seem to
But that is for fields. Not properties no?
it serializes the automatic backing field of the property
Nevermind I forgot a ! in my expression
how can i check if a ray cast is hitting a 2d Sprite in a 3d game? more specifically how can give that sprite a polygon collider 2d like collider that works with the raycast?
Oh dam.Just learned that today. 😅
Ty
Okay it works But I still have a Huge GC after 20ish loop even if I don't have any new in my coroutine
Are you using the profiler to hunt down the allocs?
What is the reason for you not being able to add the PolygonCollider2D component to your 2D sprite?
oh the raycast wasn't detecting it but after more testing i think that may be an issue with the raycast?
Do you have a link to a guide ?
Or something like that
Just a field on its own needs [SerializeField] only. Steve explained why you need to specify for a property
Alright.
after checking again the raycast simply isnt detecting the polygon 2d
but it worked when i used like a box collider
A 2D one, you mean?
no, im using sprites in a 3d game,
It doesn't seem like the issues is in PolygonCollider2D not reacing to raycasts
Well, why do you want to use a 2D Polygon Collider instead of a 3D Mesh Collider?
does the mesh collider wrap to the sprite in the same way the polygon collider does?
Yes, but in 3D
I do not - I'm not terribly experienced in this capacity 😅
But you might be able to flip on some additional info for GC.alloc from the "Call Stacks" dropdown at the top, if you haven't already.
The Memory Profiler might also provide some insights
Didnt really see anything above but turn on deep profile for more info and run it again
i don't know how to make it do that? the closest thing is giving it a quad mesh at which point its no better than a box collider across the whole area of the sprite which includes empty space
actually a quad in the mesh collider dosent get detected either but other meshs do
Well, put a Mesh Collider on your sprite and see what happens
But this is a bad idea
If that's a sprite, use a PolygonColider2D with the Physics2D's Raycast
Oh im not using a physics2D Raycast i see
SOLVED : thanks everyone ( I was adding a new delegate at each loop so at the end I was calling 1800000 time the same function x) )
yo if i destroy a gameobject will any references to it become null
Yes... sort of. It'll still point to a destroyed game object. Unity just overloads the equality operator so it will == null. But don't expect it to be null in other contexts 👀
i see
also how would i detect if something is not being hovered?
i wanna make a message show up when i hover over a button and for it to disappear when im not hovering
OnMouseExit() may be sufficient here
oh right
i can do the spawning in OnMouseEnter() too then
and deleting it in Exit
and i dont even need messageExists then i guess?
as a safeguard maybe but still
Probably not 🙃
i dont need either bools actually
Enable or disable the message depending on the method
One minor addendum: when you Destroy() an object it won't actually happen until the end of the current frame. DestroyImmediate() does it instantaneously, but at the cost of immediately incurring that overhead as well
wdym by incurring the overhead
It means don't use unless in the editor
Allocating things in memory and the "Garbage Collection" process through which destroyed objects' memory is marked as free are relatively expensive operations - both have a more notable performance impact than most other common operations and calculations. It's generally not a problem in small quantities, but it can become problematic at scale... Many the cause of a performance bottleneck is unintentionally mucking about with memory much more than you intended to 👀
As sashok says, DestroyImmediate() is best avoided apart from editor scripting
if you have a prefab and place it in the scene and you want to modify the mesh based on its unique setup from inspector - how can you do that in edit mode since unity tells you to only use shared mesh but that will affect all the prefabs not just the one specific object
even the button on it says that it's inside but it doesnt seem to work?
Ui uses the IPointer interfaces
how would i check if the mouse is inside a UI element then
Because its user has not read the documentation
i even added a collider to it to check
maybe adding colliders to ui objects isnt a good idea lmao
Implement IPointerEnterHandler and its friends https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.IPointerEnterHandler.html
It is not
Actually, IPointerHandlers are so bad..
Then don't really provide a great drag functionality
thank u very much
Someday I may implement my own interface for drag when I have to use it
im sorry i just dont work with UI often
😭
i will try to read docs and forums more before asking questions in the future ty
it works, nice :)
There is still this thing that the mouse position has to be changed while the object is held before the drag is registered
I have these properties in my Editor script.
public PlayerBuildSetup BasicSetup => Target.BasicSetup;
public PlayerBuildSetup AddArrowSetup => Target.AddArrowsSetup;
public PlayerBuildSetup MoveArrowSetup => Target.MoveArrowsSetup;
Each property has its own method, like ExecuteBasic(evt) for BasicSetup and ExecuteKey(AddArrowSetup, evt) for AddArrowSetup.
Their return types are booleans. If false is returned, the PlayerBuildSetup.Break() method should be called on the previous setup, which is unique at a time, and the "loop?" should be broken too.
I know I'm overthinking it, even wanted to enumerate through an IEnumerator with MoveNext, but how would you implement this in a clear way?
More setups may be added in the future, so the solution should be persistent
wonder if there's a way to just exclude an object from IPointer stuff?
What do you mean?
wait lemme try something real quick
well say i wanna spawn a UI object when i hover over a button
the obejct spawns, blocks the button, instantly disappears, opening the button, which means the button is being hovered again and the object spawns again repeating the cycle
and i wonder if theres any way to like, stop the object from being "seen" i guess
i would assume IgnoreRaycast layer wouldnt work? lemme try at least
nope as expected
Many uGUI objects have a "Raycast Target" toggle
didnt work, i dont think im using raycasts here with IPointer
what am i missing? i can't get any info about the new object it's pointing at during OnPointerExit, i cant edit what layer im ignoring (unless i can), what do i do
ig ill watch a tutorial
I keep getting a CS1513 even though there's a curly brace at the line mentioned.
we dont know codes
show the error
codes are for computers
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
well thats not the one its talking about then
im gonna take a wild hail mary guess its the class enclosing brace
your IDE def is not configured so fix that
how much should i subdivide my code into functions? should I have a ProcessAnimation, ProcessInput, ProcessSound etc function and call them all in Update()?
or should i just put it all in update separated by newlines
this
it doesn't matter... whatever makes your team happier
you can probably refactor this in about a minute in each direction when there's a need, so not worth spending more than 10 seconds to decide 😄
my approach tends to be: write everything directly in Update if it's just a few lines of code or would be one function anyway... if it starts to be long and somewhat complicated - splitting it better expresses what each part is about
something is null on line 17 of that SomethingSomethingBase class
MoveNext() just makes it look somewhat "scary" because its happening inside a Coroutine thats all
since its an iterator
Hey does anyone know how to create a list like the one you get when you add a component in the editor?
i have a game object with a lot of child objects that it needs to manage...
i could build it all as a prefab, but then the script needs to get references to all the children
or i could instantiate all the child objects within the script - then i'd have references to them already, but it's not as nice to look at in the scene
what should i do?
but it's not as nice to look at in the scene
You mean in the scene hierarchy?
#↕️┃editor-extensions would know... I think it might be an AdvancedDropdown, but I'm not certain
(assuming you mean to make the list for like the inspector)
I managed to figure it out. It's similar to the volume component. Unity has a class called FilterWindow with a static method called Show()
I am currently figuring it out how it works
Ooo... excellent 👌. I'll have to take a look at that, myself
oooh this seems cool, I might play around with this
took me a bit to find since I had to paruse unity's Editor api for volume component
since idk how to find the one for adding components
though if you want to see how the volume component does it, make sure you have unity core RP installed
that's where it comes from
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
sure, the hierarchy but also just being able to see everything in the scene preview thing
actually you're right it's nice to be able to look at it in the hierarchy too
I think I could also look at the c# source code on github
does it make sense to drag a game object's child to the input on its own script like this?
people were saying the GetChild() functions were fragile and it's better to have stuff hooked up through the inspector
i've hooked up stuff from the project assets (on the bottom side of the screen) before, but i'm not sure if it's ok to do it from the hierarchy like this?
i think this is what they were suggesting as an alternative to GetChild()
Yea it's good with scene objects too when available.
Heya. I've been working with FixedJoint2Ds on rigidbodies with negligible mass (~0) and trigger boxcollider2ds. I've noticed that when the fixedjoint skeleton impacts another collider, the set of trigger boxcolliders jerk into the collider they're supposed to be colliding with for a single frame and then adjust back into their normal position over the next few frames. The problem is that I have a physics-intensive project where this few-frame bug ruins everything. How can I make the fixed joints actually... fix?
i think it is a scene object - otherwise it wouldn't show up in the hierarchy, right? or am i missing something
Correct.
Hii
I'm trying to code it to where each line will play separately and I've tried changed the delay between lines but it isn't work either and I'm getting no errors so idk what the issue is?
The Start function is called on all your dialog lines since you wait before continuing the loop to disable them.
lmk if you need more help!
so like this?
no, if you look this will wait in the middle of the loop that is disabling all your dialogue objects and so Start will still run on those not disabled.
OHHHHh
lmk if you get it! If you can't get it I can give you the code but it's important to learn to debug your code!
yessir
can an Action have a return type?
bool requestNewState(int handleIndex, bool newState) {
if (!newState) {
if (activeHandleIndex != handleIndex) {
Debug.LogError("Permutor got into illegal state!");
return false;
}
activeHandleIndex = -1;
return true;
}
if (activeHandleIndex != -1) return false;
activeHandleIndex = handleIndex;
return true;
}
for (int i = 0; i < workingRows; i++) {
handles[i].Init(i, requestNewState);
}
this isn't working
I think you're looking for Func<T,TResult>
those are the inputs
public void Init(int handleIndex, Action<int, bool> callback) {
state = false;
this.handleIndex = handleIndex;
requestNewState = callback;
animator = GetComponent<animator>();
animator.SetBool("initialized", true);
}
ohhhhh
but i was using 2 type parameters before when it was void return type
oh you pointed me to func not action
what class were you using?
I'm assuming this method satisfies the delegate
i'm not sure what that means
in here, what is requestNewState? Can I see how you declare it?
yeah let me just give that whole class since it's small
public class PermutorHandle : MonoBehaviour
{
private bool state;
private int handleIndex;
private Action<int, bool> requestNewState;
private Animator animator;
public void Init(int handleIndex, Action<int, bool> callback) {
state = false;
this.handleIndex = handleIndex;
requestNewState = callback;
animator = GetComponent<animator>();
animator.SetBool("initialized", true);
}
void OnMouseDown() {
if (!requestNewState?.Invoke(handleIndex, !state)) return;
state = !state;
animator.SetBool("active", state);
}
}
ok yea cool, just wanted to check you weren't trying to do something funky like an event with a return type.
this is a child object talking to its parent
i'm not sure what you mean, requestNewState does return a bool
but as long as it looks good to you
🙂
yes, but delegates are often used with events, and an event does not return anything, so I wanted to see how you were trying to use it to make sure that was not the case.
i'm getting this error
Assets/Permutor/PermutorHandle.cs(22,13): error CS0266: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
that's on the line with Invoke()
oh do i not need that ? syntax for Funcs?
woo no compile errors
thanks
no you should definitely have the ? or null check it in some way
im not sure about the specifics but for some reason it won't cast ? to a bool in the if statement (i think for numbers it does just fine tho?). You can just do this:
if (requestNewState?.Invoke(handleIndex, !state) != true)
Okay i cant tell if i solved the problem now because after changing some things now the text wont show up
it's because the ? evaluates the expression to null if what is on the left of it is null so since the Func returns bool, the expression returns bool? since the func could be null
it can be null checked on a separate line though and then invoked for the if statement just fine
oh yea huh. If they did if (requestNewState?.Invoke(handleIndex, !state) != true) it would work cus null is not true duh (this is also why it works in other situations but not bool cus I shorthand it a lot).
well no, that would have the same error because you're still trying to cast a nullable bool to bool. you cannot use the null conditional operator in the condition because of that. so it just needs to be null checked separately either as a guard clause on the previous line or as the first condition of the if statement if(requestNewState != null && requestNewState.Invoke(...))
Well, you're still pausing in your loop while the text is being disabled.
This is not true at all. You do not need to cast to compare two different types
it's just that you normally wouldn't compare two different types because it always returns false (unless one type can implicitly cast to the other)
ok well i guess it's true a little bit. I think it's with value types and not reference types, my mistake. Or maybe it's that null can compare to any type? Whatever the case, null can compare.
Ok, so it's true a little bit. You don't have to cast when you compare something to null because it always returns false.
no, the first works because Nullable<T> likely has the equality operators overridden not just because null can be compared to other objects
null can be compared to other objects, 100%
i'm not saying it cannot
i'm saying that the reason bool? != bool works is because Nullable<T> likely has the equality operators overridden. (bool? is literally just shorthand for Nullable<bool>)
yes I know, but in your original message you said I'd have the same error bc of casting. We were both a little wrong :)
i've gotta read this tomorrow, my mind is fried right now lol
yes i get that. but you attempted to correct me again about something i did not say in my followup
oh sorry you are correct! Sorry, I just got a new monitor and everything is smaller on it than my old one haha. I'll try to read more carefully
There any kinda of global setting to cap Unity's memory usage? I dialed a variable up too high and before I could figure out what was even going on it had sucked up 20 gigs on me
I don't think there is. Besides, if there was, it would just crash your editor without any good way to debug it.
looks like one alternative is to setup a coroutine that checks System.GC.GetTotalMemory() and if above some level just call Application.Quit() and log a message
I don't think Application.Quit works in the editor.
But you could throw an error I guess.
private void EndGame()
{
Application.Quit();
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
}```
This seems to work
I could barely get task manager to pop up it was so full lol
You call Application.Quit regardless of it being the editor or not here
private void EndGame()
{
#if UNITY_EDITOR
if (EditorApplication.isPlaying)
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
for some reason, this is visible for a frame before the horizontal layout realizes it's mistake
forgiveness to nest haters
the categories content has a horizontal layout group, I need the text width to be scaled though. I just noticed content size filter has a warning for layout groups, but how do I make it so the text and the button respectively size to fit a single line of the text without wrapping
How can i Code my own 3D camera, Docs and stuff, no cinnemachine
By coding it and writing the docs..?
I'm not sure what exactly you're asking here.
friends, I'm using unity hexagonal pointy topped tilemaps. I want to make a custom method for getting GetCellCentreWorld. I want to a custom method so i can use it in Jobs. I'm having trouble finding the resources to implement this. has anyone done anything like this?
Quick question; If I make this field in a class public static readonly Texture2D BlankTexture = new(128, 128); does that mean that every new instance of the class has this field, meaning higher memory footprint, or would the instance be shared?
My gut says it's shared but just wanted to double check
does anyone know how to disable this log in unity andriod
Its static, the instance does not have the field at all. Its associated with the type
Dont crosspost, keep it in #💻┃code-beginner and look at the #854851968446365696 on how to ask properly
then go help me there lmao
So my gut is correct. Thanks.
You havent even asked a proper question 🤦♂️, but now I will specifically not help you.
https://stackoverflow.com/questions/14781993/how-exactly-do-static-fields-work-internally
Theres more information here if interested
Since the text is a child of the button, you can just use anchors to fill the width (and optionally the height if youd like), this will auto-size with the button - then you would only need the content size fitter (and some kind of layout group) on your button - however, layout groups refresh at specific times, so you may either need to force changes (which could take at least 1 frame to register) or you need to manually call a refresh of the layout - for a manual refresh, you can try some of the solutions mentioned here: https://discussions.unity.com/t/force-immediate-layout-update/608126/12 (either forcing the canvas to update, using a coroutine to toggle components and wait a frame, forcing the layout group to recalculate, or forcing the layout to rebuild) - alternatively if none of that works you can also calculate and position/resize elements yourself with their RectTransform and choose when to update it instead of using a layout group, albeit this approach is a bit more complicated and involves some math (but gives you more control and possibly a performance increase over the component)
i want to make a souls-like game, but im not sure where to start on the movement, and how i could get it to feel like it does in souls like games.
could someone help?
I think there are several tutorial series on youtube for souls-like games.
Maybe start from going through the tutorials.
or i did something wrong
most likely that
Unity didn't change that much in the last 10 years in terms of what you'll use for character controllers, so it's unlikely that they're outdated.
As for it not working, there's not much we can help you with that. You just need to go back and rewatch the tutorial and make sure you followed it correctly.
Also, maybe go one more step back, and go through unity basics first. That would help you identify things you might be doing wrong or missing. And actually help you understand what they're doing in the tutorials, instead of just blindly following them.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If there's any specific problem that you struggle with debugging, feel free to share the details.
Hello guys, im not sure if its proper channel, but let me start from here. I do struggle with building a game for iOS since i moved from 2021.3.15f1 to 2022.3.34f1. To be more precise it finishes build but when it comes to archive stage it fails with error
ld: library 'x' not found
where x looks like my bundle identificator (mygame.dev.testflight)
I've read through all forums and didn't find solution yet
Hey, I've made all my game for HD res and I'm trying to set it so that there'll be black bars on the sides when there the aspect isn't 16/9.
So far I have problems with the UI and so I'm considering to switch the match with width/height depending on the aspect ratio of the resolution.
Is this a sensible way to do things? I don't want to redo the art for all resolutions. I have no idea how games with 2D art tackle that problem.
does yield break wait for next frame before exitting the coroutine or does it in that same frame?
Maybe better to ask in #📱┃mobile
Should be on the same frame I think.
ty!
Code looks fine by itself (you can invert newSetup != currSetup check to be a guard clause too)
Can't really give more suggestion without knowing what it's meant to do. Is it for some kind of step by step process?
It ends it immediately but functionally what would the difference be? The point is no further code after that line will run, period.
For my use case I think it may make no difference, so I was just trying to understand it. Hypothethically I was thinking maybe it would make a difference in race conditions edge cases but I think its not relevant. Like I was thinking of something that would check if that coroutine was still running every frame how it would be affected by the difference of yield break waiting for 1 extra frame. But there are better ways to do that.
Yes, it's meant to execute the first Setup and don't check the other ones
I just don't like how these returns in the 2nd method look
I first thought about creating an IEnumerator and yield return these methods, but it wouldn't look fine, as would need to use a tuple (bool, Setup) to check for Current
There is no way to externally check if a Coroutine is still running
It's hard to say without context, but I have a feeling that you are doing something along the line of "once a step has started, wait for a specific event which signifies the completion of that step, then move onto next step, etc."
If that's the case, it's honestly a perfect use case for async/await (or coroutine).
yup, realized it when trying to think of a hypothethical 😛 I usually just set a reference to it before running and then set to null when its done, and at that point it does indeed not matter what yield break does if its after setting that reference null
No, that's not it. The code I've implement does exactly what I want, I'm just afraid it doesn't look fine.
I currently have 3 Setups, but more can be added in the future.
ExecuteKey returns true if the Setup's current option is not held. If false is returned, the suitable Setup is found and the previous Setup has to be replaced by it if it differs.
So that's the thing.
ExecuteKey
Is the suitable key binding selected for the Setup's process?
Yes? Return false and select this Setup
No? Return true and go check whether the key binding is suitable for the other Setups
Im curious if anyone here can find a flaw that I can’t. I have a script on all of the randomly generated foxes on my game called FoxBaseBehavior.cs. They also all use Navmesh path finding. However I’m not putting this in there because I don’t believe it’s related to my issue.
Everytime a fox enters a den all other foxes briefly disappear for a frame or two. Here’s the code snippet for how foxes handle entering dens
private void DenEnter(List<object> list)
{
string denType = (string)list[0];
if (_myStats.At.Name == denType)
{
ChooseRandomizedLocationFromPlace(denType, false);
gameObject.SetActive(false);
}
}```
If you’re wondering why it’s a list basically I need to pass along extra information in that specific method for other areas of my game
Notably, I wonder if everytime one fox enters a den assigned to another fox, it triggers this on that fox as well
I just don’t know how it’s possible that could happen since this is a private method,so it correct me if I’m wrong: it would ONLY trigger for that specific fox game object
I think if private it would only work on the object the script is on. you can print objects in the list and maybe one is in there that shouldnt be? if so find out why.
Why are you using a List<object> and then casting the first element to a string?
Why not make an actual type?
anyway this is way too little information to know what's going on
we need a lot more context
but from this snippet there's a lot of questionable stuff going on.
There is other information in the list that isn’t a string
right so why not just make a class that has this information
instead of a random grab-bag List<object>
they said because the list contains other information. I think thats a pretty bad way to do it though. praetor approach is better.
Im using the send message syntax and that only lets you send one argument of information
public class DenInfo {
DenType denType;
int numberOfFoxes;
Color foxColor;
}``` for example
We have a system similar to that, this is about sending information from one script to another
you mean GameObject.SendMessage? That's another red flag tbh 😬
It's impossible to work with/debug systems like this with no type safety
errors in this system could easily be the source of your problem
anyway in regards to the original problem, you'd have to share a lot more context and code.
True this is one of the first things I coded and I haven’t touched on it in almost a year, I should probably make it a event
I would resolve your bug then optimize into alternatives after. you dont want to create more issues amidst dealing with another.
My character is set up to move when I click to World Space. BUT if I click on UI they do not move. (That’s what SHOULD happen, and DOES while in Game mode)
When I’m in Simulator mode it does both at the same time. For example if I click on a button, it’s triggered AND I move to that location. If I keep clicking on any UI after this it will ONLY interact with the UI. When I click on World Space it still assumes I’m clicking on the UI for that one instance (Even if I click on a World Space). If I click on a World Space a second time I can move again.
My EventManager has all its needed components and I’ve restructured my Movement script to check for any synchronous functions. I really don’t know what else to do. Does anyone have any ideas how I can fix this?
please I'm begging for any kind of solution. I've been stuck on this for 2 days and nothing works
you would have to share how your code actually works
but basically - for a touch screen there's not really a "pointer" hovering over stuff. So if you're doing the EventSystem.current.IsPointerOverGameObject thing, it's not going to work
the solution here is to use the event system for everything and you get the UI blocking behavior for free
ARE YOU KIDDING ME?
that's it?!
I kid you not
so something like? GameEvents.current.s_DoTheThing();
my god
I got experiementing to do
thank you so much!
im wondering how i could make a movement system that doesnt use rigidbody for a platformer
Yes, you are free to use CharacterController, Transform etc.
thanks!
Also, a dynamic rigidbody and kinematic one are quite different. Worth looking into the differences
Call a sound manager which does it for you
is pathway down ? I just checked pathway on unity and it's got 404
un-fucking believable
Why have you received the answer "is this a code question?" in #💻┃code-beginner and reasked it in #archived-code-general?
I guess because im dumb
I've started using the new Input system and it's saying the method is running twice when I give it an input
{
public void move(InputAction.CallbackContext context)
{
//Debug.Log("Clicked on the WORLD");
if (context.performed)
{
Debug.Log("Clicked on the WORLD " + context.phase);
}
}
}```
I don't get it
How did you hook this code up to the action?
How many player objects do you have in the scene?
just the one
You sure?
public class TestMovement : MonoBehaviour
{
public void move(InputAction.CallbackContext context)
{
//Debug.Log("Clicked on the WORLD");
if (context.performed)
{
Debug.Log($"Clicked on the WORLD {context.phase} on {this.gameObject.name}");
}
}
}```
let's see
(the scene is a mess while I get things sorted so just ignore all the disabled stuff)
if you remove the move binding from here what happens?
in the callback context?
ok that's certainly weird
Can you show a screenshot of your action?
I.e. from the input action asset?
You might have some weird interaction or processor setup on it
like maybe you have the Press and Release interaction
With Pass THrough on you'll get a performed event for any change in the control at all
thank you. this thing is giving me a headache while I learn it
Yeah it has a learning curve
do you mind helping me with something else that should be super basic?
btw #🖱️┃input-system exists if you have further input system questions.
You can ask whatever you like but I can't commit to helping with it.
thanks again
Hello!
Im trying to create a Codeless IAP button that purchases everything but i have to calculate its value at runtime.
After i get its value and i set its product ID to the ID that corresponds to its price i want to also update the text component that display its price.
I know i can update the value in the OnProductFetched listener but i was wondering if there is a way to do it outside the listener.
IAP Manager:
using TMPro;
using UnityEngine;
using UnityEngine.Purchasing;
public class IAPManager: MonoBehaviour
{
[SerialzieField] CodelessIAPButton IAPButton;
private float price;
private float[] validPrices = { 9.99f, 14.99f, 19.99f, 24.99f, 29.99f, 34.99f, 39.99f, 44.99f, 49.99f, 54.99f, 59.99f, 64.99f, 69.99f, 74.99f };
private void SetIAPButtonValue(int index)
{
price = validPrices[index];
IAPButton.productID = $"purchase_everything_{price}usd";
// Now after i set the id i would like to also update its text component so i was thinking of calling the .onProductFetched() but it doesnt work
}
is there a way to atleast acces the product of the IAPButton after i set its ID?
what you're doing makes no sense. You'd create a product ID that represents purchasing everything and hook the button up to it. Unless you set up that product ID on the store side, you'll just get an invalid product id with what you're doing here. And since it's already set up on the store, you hook the button up to that product id. Hence the codeless part
public static List<Transform> GetEntitiesInRange(Transform originTransform, float range, string entityLayer)
{
Collider[] colliders = new Collider[0];
Physics.OverlapSphereNonAlloc(originTransform.position, range, colliders, LayerMask.GetMask(entityLayer));
var entities = colliders.ToTransforms();
// Remove self
entities.Remove(originTransform);
return entities;
}
I'm not really sure why but when I walk my character into range of the AI it should be hit by the OverlapSphere but its not
Even if I walk right up to it
Your collider array size is zero
it can never hold anything
Ah
I kind of just assumed it made a new array anyway and assigned it
how am I supposed to know how much to allocate though
it really wants me to use the NonAlloc version, the IDE complains if I don't
This is the typical pattern:
static Collider[] resultsArray = new[10];
public static List<Transform> GetEntitiesInRange(Transform originTransform, float range, string entityLayer)
{
int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
for (int i = 0; i < count; i++) {
Debug.Log($"Overlapped {resultsArray[i]}");
}```
The whole point of NonAlloc is to reuse an existing array
if you just create/allocate a brand spanking new array each time, it defeats the purpose of NonAlloc
oh it wants me to cache them
In my example I used 10. It's a matter of asking yourself "What's the highest number of objects I expect this query to find and reasonably handle in my code?"
well it'd be kind of weird to cache this in my utility class
I guess I could put it in the parameter list of the method
you dont have to, and the method doesnt care or cant even check if its a local variable
btw returning a fresh array from this method also defeats the purpose
you should have this method return int and take in a results list or array
this is how i had it before
i.e., follow the same pattern as the nonalloc query
oops covered it
public static int GetEntitiesInRange(Transform originTransform, float range, string entityLayer, List<Transform> results)
{
int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
int resultCount = count;
for (int i = 0; i < count; i++) {
var xForm = resultsArray[i].transform;
if (xForm == originTransform) {
resultCount -= 1;
continue;
}
results.Add(xForm);
}
return resultCount;
}```
This is how I recommend you implement this
if you want to go the nonalloc route
if you don't mind allocating memory each time, just don't use nonalloc
You could also do this (clear the results array each time):
public static void GetEntitiesInRange(Transform originTransform, float range, string entityLayer, List<Transform> results)
{
results.Clear();
int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
for (int i = 0; i < count; i++) {
var xForm = resultsArray[i].transform;
if (xForm == originTransform) {
continue;
}
results.Add(xForm);
}
}```
dont I need to pass in resultsArray?
no it would be a static array as per my previous example
I'm doing this because you wanted a List result
if you want an array result you can just pass the result array in, sure. But that won't let you do the thing where you ignore the "originTransform"
since arrays cannot be resized.
that being said - i highly recommend just using a layermask to do that
a layermask to do..?
to ignore the object you want to ignore
wouldn't that require a layer for every individual entity
no?
well all entities are on the same entity layer
It would ust require the things you're looking for to be on a different layer than the thing that is "performing the query"
remember I don't really understand your game
or know any context here
you could temporarily put it on a separate layer to do the query, then set it back
otherwise, use the list approach
The purpose is this is a method in an AI Utility class, its meant to return a list of the other "Entities" within a range of it (excluding itself)
alright well I've explained two different ways you can do that
so, for the static array, i guess its more efficient because im not creating/destroying an array everytime but just modifying an existing one?
because the other way i was doing it, i would be making an array and then it would be deallocated once GetEntitiesInRange is returned
(at least thats my understanding?)
yes
yes, it would be used just once and then garbage collected
which is wasteful
by the way, same with the list
that's why I suggested a version where the list is passed in as a parameter
im trying the second one now
static readonly Collider[] resultsArray = new Collider[256]; // More efficient to reuse this array than to create a new one each time this method is called
public static int GetEntitiesInRange(Transform originTransform, float range, string entityLayer, List<Transform> results)
{
results.Clear();
int count = Physics.OverlapSphereNonAlloc(originTransform.position, range, resultsArray, LayerMask.GetMask(entityLayer));
for (int i = 0; i < count; i++)
{
var xForm = resultsArray[i].transform;
if (xForm == originTransform)
{
continue;
}
results.Add(xForm);
}
return count;
}
Usage:
if (AIUtility.GetEntitiesInRange(_nav.transform, _sightRange, _entityLayer, _entitiesInRange) > 0)
{
SetTargetEntity(entitiesInRange: _entitiesInRange);
}
else
{
ClearTargetEntity();
}
I am a little worried if keeping a static results array in the utility class is a bad idea
yeah if your goal there is to check for anything in range or not that works
But you could also use CheckSphere for that
which doesn't allocate anything at all
how so
well because I'd have a bunch of entities calling this and it'd be constantly modifying this same array
It's probably not I just don't fully understand what im doing yet
So CheckSphere would be more efficient?
Anyone know how to get the PostProcess attribute working?
If you just want to know if anything is in range, yes.
!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.
im not sure where to put it because it's both scripting and graphics, I could try there if I don't get a response here
I'm trying to see what is in range, Im guessing when you say "anything " in range you're saying that CheckSphere would work if I'm just trying to see if any singular collider is within the sphere
Yes if you need information about the things you wouldn't use CheckSphere
but the Usage example you showed here is just checking if the number of things in range is greater than 0
and that's where CheckSphere works
Oh but
I guess it doesn't
because of your whole "ignore myself" thing
It's setting the results array
CheckSphere returns a boolean which doesn't really help me
i need to know whats in the sphere
well in the case I was describing you wouldn't have needed to know
so does that memory thing mean i should be having these variables as static fields too in other methods?
public static bool EntityInSight(Transform originTrans, Transform entityTrans, float sightRange)
{
Vector3 origin = originTrans.position;
Vector3 direction = entityTrans.position - origin;
_originalLayer = originTrans.gameObject.layer;
originTrans.gameObject.layer = 2; // 2 = Ignore Raycast
if (Physics.Raycast(origin, direction, out RaycastHit hit, direction.magnitude))
{
originTrans.gameObject.layer = _originalLayer;
return hit.transform == entityTrans && direction.magnitude <= sightRange;
}
else
{
originTrans.gameObject.layer = _originalLayer;
return false;
}
}
for example here the two Vector3s
or is this something already optimized by the compiler/GC?
Vector3 is a struct
it's a value type
it will just be allocated on the stack
there is no garbage collection involvement
tbh i've been programming for a while and still don't completely understand what 'the stack' is
the stack aka the callstack. It's how the program handles calling functions and then returning back where it was
it's uh...
maybe hard to explain if you haven't taken a systems programming class...
ive barely even taken a programming class
but the point is, local variables for value types are basically free.
i did take a C# OOP class but i didn't learn anything that i didn't already know
alright
is there an easy way to tell value types apart from reference types? (i think thats the alternative to a value type?)
Yes - all struct are value types. All class are reference types
any type you look at in C# will be one of those two
crucially that includes basic types such as int, float, etc..
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types
and im assuming the difference between a struct and a class is that the allocation for a class is dynamic size-wise, but for a struct it will have to re-allocate everytime its modified?
no, it's not about the size being dynamic
classes also have a static size
it's about where it gets allocated and it's about how it gets passed as method paremeters/return types
if you do new MyStruct() it goes on the stack.
If you do new MyClass() it goes on the heap.
And structs get passed to and from methods by copying the value
Whereas classes get passed to and from methods by copying a reference to the object in heap memory.
the reason classes go in the heap is so that you can pass around references to them and be guaranteed that the reference will be valid
the stack is constantly getting written over whenever new functions are called and finished, so you can't guarantee an object in the stack will still be there later on.
