#archived-code-general
1 messages · Page 200 of 1
Yeah I don't want the ai to see through walls
so use ray casts, would that not be performace heavy as well?
It sure has a considerable impact.
You would need both anyway.
You need to compare the angle between the transform.forward of the enemies and the vector form by the player and the enemies
If the angle is lower than a threshold, then it is visible.
alright i get you
This is normal, using raycasts is fine. You can even use a check to limit how often you update the check . . .
oy lads. i have an object that basically acts as a button, and i wanted to know what might be a good method to make it so the button can do multiple things, such as unlocking a specific door, spawning an item, resetting something, etc. i reckon i could do this by just duplicating the object and making several scripts for unique cases, but i don't think that's very efficient
UnityEvent
public UnityEvent StuffToDo;
public void ButtonPressed()
{
StuffToDo?.Invoke();
}```
make a prefab out of button, you can then assign each button a different method or multiple ones in inspector for field StuffToDo.
Can anybody think of why my playercontroller wouldn't be working when I build the game, but would be working in the editor?
Do any of your inputs work?
In the editor they do
What would i need the value of
In the built game, I mean
Nope, but I think I'm figuring it out
I would use OnGUI() to display input values
I believe it has to do with the script execution order
I'm getting a null reference in the built version while the editor doens't have that
ah
try restarting your editor. that can reveal execution order problems
the order of objects will be different
I've caught a few issues after doing that
(loading a different scene might be enough)
I might try that, but I think I have it fixed
I was just thinking about that today, actually
It would be nice if you could scramble objects to try and suss out that kind of problem
I would look specifically at the innermost if statement:
if (__instance.gameObject.GetComponent<BoxCollider2D>().IsTouchingLayers(owp))
Is it returning the box collider actually? is the IsTouchingLayers call returning true? Is owp what you thought it was?
Is it even the gameObject you thought it was?
Btw, why not just do if (box.IsTouchingLayers(owp)) since you cached the box collider right before this?
I'm thinking the IsTouchingLayers call is the issue, since you DID cached the box collider and used it already without a nullrefexception
Also, I'm confused by this:
box.transform.position += new Vector3(0, 0.2f, 0);
//...
__instance.transform.position -= new Vector3(0, 99, 0);
Since box is the BoxCollider of __instance, you are modifying the same exact transform on both of those lines. You are telling it to go up .2, and down 99.
But if I understand you right, NEITHER of those things are happening?
Wait, as I look more, I keep getting confused.
You have this:
foreach (var obj in Resources.FindObjectsOfTypeAll<GameObject>())
{
int owp = LayerMask.NameToLayer("OneWayPlatform");
if (obj.layer == owp)
{
where you find EVERY GameObject in the game, then set owp to OneWayPlatform over and over again for each one, then check if the gameobject is on that layer?
Why not just have a component on the platform and do FindObjectsOfType
Or better yet, have a list of the OneWayPlatforms and iterate that
Or EVEN better yet, use a raycast to just see what the player is standing on instead of iterating anything
Respected,
I want to move the gameobject forward and slightly upward too and rotate slightly in the local y-axis (with rigidbody add force)...
when user finger swipe up the screen.. please guide
hey yall i got a question
im currently working on a vr game and i want to obscure the players view when they start the level
the way the people before me did this is that they have a giant gameobject thats black and they change the alpha of the gameobject to make it not transparent
this works but there are a few things that don't get blocked out by the gameobject and im struggling to figure out why it doesn't
anything that emits some kind of light shines thru it
is there a different way I can implement this?
then when its transparent things start showing thru the block
whyyyyy
i turn the alpha to 0 and u can see things but theyre all blocked by the thing
except for that stupid ass plant over there
its really hard to see whats specifically showing through in a small screenshot of a camera preview. maybe you can use something on a canvas to restrict view instead of a giant object
u can see the lil green spec srry for the bad sc
stuff shouldnt still show through your object if its alpha is set to the max, unless the geometry is kinda weird
i messed around with the way its rendered
setting render queue to alpha test makes it not show up
canvas?
like a UI object
pretty sure the object is on a canvas
the black fading block is what im talking abt btw
ah when you said giant i assumed it was not on the canvas
thank you bro
clutch af
im unsure how i helped but 🙏 glad its fixed
I forgot that it was attached to a canvas
the camera wasn't attached to it
and it was on the wrong layer
is there a way to select serialized scripts from a wrapper class? I am making an inventory system, and currently I have a serialized class Item that has an instance decleared in a mono attached to a game object. Obviously I want to have different types of items all with different stats, animations etc... Would there be a way to choose which serialized class you want to wrap onto the G.O. (choosing between children of the item class), or would I have to make wrappers for each child?
I don't know too much about ScriptableObjects so this might be a dumb question, but I have one for "Dimensions", some are presets, but I'm planning on having procedurally generated dimensions. Would it be a bad idea to generate ScriptableObjects for each new procedural dimension, or should I stick to keeping those for presets only?
What's the use case here? Are you generating them at editor time and insterting exact data into the gui, or is this some runtime generation?
Runtime
Well, you can write to scriptable objects, but you can also just use plain c# classes in this case
Is there a way to get the face normal of a collider? I have a position close to the collider and im using collider.ClosestPointOnBounds(position) to get the closest point, but is there a way for me to also get the normal of the face where this point is?
not entirely sure if theres a built in for this, maybe you could raycast towards that point and use hit.normal from the raycast
so something like this u mean?
Vector3 direction = closestPoint.Value - position;
RaycastHit hit;
Physics.Raycast(position, direction.normalized, out hit, Mathf.Infinity, 1 << 0);
PaintDecal(closestPoint.Value, hit.normal, closestCollider);
This seemed to work although there are some scenarios when the direction is 0 which doesn't really work
Hey I wrote
"public List<List<Job>> data;"
to contain jobs for a 2d grid and to itterate through it, I was told I can simplify it using
"foreach (Job job in data.SelectMany(jobList => jobList))"
I don't understand the parameters of SelectMany... I don't understand why I write "jobList" twice
Can someone maybe help me understand it? It seems a bit weird to just write it twice, especially when I don't appear to use that variable anywhere else
It's a lambda expression that just tells SelectMany to use the list as is without modifications
I think I kinda get it? Thanks
maybe you'll want this since it says
Casts a Ray that ignores all Colliders except this one
https://docs.unity3d.com/ScriptReference/Collider.Raycast.html
to ensure it hits the correct thing
ah yeah, i'll try that ty
how can i repeat an action X amount of times every X seconds
like if i want it to be repeated 3 times with a 2 seconds break between each time
I suggest you use this timer lib https://github.com/akbiggs/UnityTimer
ty
The point is that you just specify the actual question, providing reasonable context to allow us to help you. You don't ask for the actual help, because people are not going to answer that.
#854851968446365696 -> 🤔 Asking Questions
Please use the right channel for your question. This is a coding channel. #🔎┃find-a-channel
Hello, when i try to create an array its just creates random count for array
because you are not CREATING an array with that statement you are just DECLARING it
You can modify what the editor specifies in terms of size and what it contains. The editor is eventually the part that creates an instance of the array.
Ah thanks i dont know very well
But why the purpose of randomness?
🤷♂️ Just change it
normally when you declare an array or list without creating it the inspector will chose a length it has formerly used
Unless you have an attribute above it I could not think of a reason
Okay thank you so much guys. If it wont be a problem for me in future i will make it
I'm trying to control a ball using torque
but the ball is going in random directions
Torque is expecting a set of euler angles.
You're passing in direction vectors
Basically you're passing in random nonsense
Hi, I have this struct:
[Serializable]
public struct PlaceableItem
{
public ItemSO ItemSO;
public int ItemCount;
public Action<int> OnCountChanged;
public int MaxItems;
[Tooltip("Amount the item should move for when switching planets")]
public float HideOffset;
public NashSet<GameObject> PlacedItems = new NashSet<GameObject>();
}
It works good but the new NashSet<GameObject>(); is giving me an error because you can't initialise things that way when using a struct.
I need it to exist because I need to access it's count and other properties and having to do an if check and assign a new value to it every time I wanna access the property is painful.
Is there anything I can do about this?
not really, this is just how structs work! you'd need to make it a class if you want to do anything other than zero initialization
I see, the reason I went with a struct is that it's easier to serialize it in the inspector.
Is there a way to achieve this with a List<PlaceableItem> which are a class as well or would it require some custom inspector?
classes and structs are pretty interchangeable in unity's serialization system, minus a few caveats, what problems were you having?
iirc serializing a class will just give you a field to drag in an object w that script attached or sm similar(I might be wrong) while structs display all the values
let me re-check that
you get that if you make a class that extends ScriptableObject, but a plain C# class with [Serializable] works mostly the same as a struct
I see, so if it's inheriting from a MB or SO then it's displayed as a field and if you use a class without inheriting from unity things you get all the properties displayed in the inspector, thanks!
yup!
It's giving you an error because there's no such thing as a "NashSet"
"HashSet" is a thing though
Is it possbile to crate a SpeedTest method to check user speed from Unity?
I've done this simple script:
{
private string url = "https://link.testfile.org/15MB";
void Start()
{
StartCoroutine(DownloadAndMeasureSpeed(url));
}
IEnumerator DownloadAndMeasureSpeed(string url)
{
Debug.LogWarning("SpeedTest STARTED");
UnityWebRequest request = UnityWebRequest.Get(url);
float startTime = Time.time;
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
float downloadTime = Time.time - startTime;
float fileSizeInBytes = request.downloadedBytes;
float fileSizeInMB = fileSizeInBytes / (1024 * 1024);
float downloadSpeedMBs = fileSizeInMB / downloadTime;
float downloadSpeedMbs = downloadSpeedMBs * 8; // Convert from MB/s to Mb/s
Debug.LogWarning("File size: " + fileSizeInMB + " MB");
Debug.LogWarning("Download speed: " + downloadSpeedMBs + " MB/s");
Debug.LogWarning("Download speed: " + downloadSpeedMbs + " Mb/s");
}
else
{
Debug.LogError("Error downloading file: " + request.error);
}
}
}```
the problem is that there is a significant discrepacy between this output on editor (15Mb/s), build (0.5Mb/s) and a google speedtest (50Mb/s). Does exists some better ways to do it? and could it be reliable in the first place?
I made nashset, it's basically a hashset that has an OnCountChanged event
Then make sure it's accessible (no errors, correct namespace if you have one)
Hey, I am trying to make a procedural terrain generator, everything is fine other than the textures seem very blocky and low quality despite that the alphamap resolution is 4096 and the textures are 1024x1024.
Here is my code to generate textures:
private float[,,] GenerateTextures(int index, TerrainData data)
{
Debug.LogFormat("Generating textures for island: {0}", index);
var textures = TerrainSettings.TextureSettings.Textures;
List<TerrainLayer> layers = new List<TerrainLayer>();
for (int i = 0; i < textures.Count; i++)
{
layers.Add(new TerrainLayer()
{
name = textures[i].Texture,
diffuseTexture = AssetManager.instance.FindTexture(textures[i].Texture),
normalMapTexture = AssetManager.instance.FindTexture(textures[i].NormalTexture)
});
}
data.terrainLayers = layers.ToArray();
float[,,] map = new float[TerrainSettings.HeightMapResolution, TerrainSettings.HeightMapResolution, textures.Count];
for (int x = 0; x < TerrainSettings.HeightMapResolution; x++)
{
for (int y = 0; y < TerrainSettings.HeightMapResolution; y++)
{
for (int z = 0; z < textures.Count; z++)
{
var texture = textures[z];
var height = NoiseMap[index][x,y] * 100;
bool valid = (height > texture.MinHeight && height < texture.MaxHeight) && (texture.BiomesToSpawnIn.Contains(BiomeMap[index]));
map[x, y, z] = valid ? 1 : 0f;
}
}
}
data.SetAlphamaps(0, 0, map);
return map;
}
well, how big is the terrain?
Is the terrain is 1km x 1km, and your splatmap texture is 1024x1024, you get around 1 pixel per meter
If you want to have, say, ten pixels of blending between the grass and the sand over the span of one meter, then your terrain should be 100m x 100m
Ah okay. Thanks.
You can also try blurring the splatmaps
It looks like you're setting each one to one -- and only one -- layer
So you're always going to have hard edges
I dunno if there's any built-in way to do that, but you could just do a simple box blur
naïvely, you'd iterate over every cell and set the value to be the average of the surrounding 9 cells
but you could also just do a horizontal pass and a vertical pass to make it faster
but at that point, I'd probably be looking at using a compute shader. You could do a nice big blur on the GPU very quickly.
i'm having an issue where float precision is shooting me in the foot, i have two nodes which i want to test if a character controller can reach the position (for AI navigation purposes).
however, this single 0.01 difference which i have no idea where its comming from is causing my comparasion to return false, which in result causes a link between the two positions to not be built
how can i fix this... presicion issue?
since its such a tiny value i was thinking about somehow removing such small presicion. but i dont know how i would do that
its quite annoying since it sees to be a specific issue with the mesh collider these tiles are using
what kinda comparison
show
because well, just using a regular box collider doesnt have the impresicion issue
kk
_mover.DestinationPosition = nodeBPosition;
Physics.SyncTransforms();
for (int j = 0; j < 5; j++)
{
_mover.Move();
}
if (_mover.MoverFeetPosition != _mover.DestinationPosition)
{
continue;
}```
are those vector3s
hmm they use approximity behind the scenes so not sure it would be floating point imprecision
can't tell by this alone , would need to see more of the setup
yeah, i am aware, as i said, the issue seems to be with a mesh collider that i'm using from the assetstore i have
or at least thats my hunch yknow
either that or an issue i'm facing with the character controller itself, i did make sure to account for the skin width of it
public Vector3 CapsuleHalfHeight => new Vector3(0, (_moverCharacterController.height / 2) + _moverCharacterController.skinWidth, 0);
public Vector3 StartPosition { get; set; }
public Vector3 DestinationPosition { get; set; }
public Vector3 MoverPosition => _transform.position;
public void SetMoverPosition(Vector3 value, bool shiftByCapsuleHalfHeight)
{
value += shiftByCapsuleHalfHeight ? CapsuleHalfHeight : Vector3.zero;
_transform.position = value;
}
public Vector3 MoverFeetPosition => MoverPosition - CapsuleHalfHeight;```
The difference is in the y position. It is saying one of the positions is slightly above the ground. This is more than just floating point impricision
I usually check a distance for if it's close enough, so they don't try to circle something if blocked
i guess i could actually check for distance instead
but yeah, i know the issue itself, its not exactly a difficult fix
what bothers me is that this is only happening on what i assume is a mesh collider
because on a simpler collider, such as a box collider, this doesnt happen
which just confuses me
but yeah i'll go ahead and just compare distances
better than staying all day trying to fix such miniscule issue
Ah, you're deriving the feetPosition from a division and subtraction, I take it back, this COULD be impricision
Yeah I'm not sure the fix though, sorry
yeah this is a head scratch for me this early morn xD
i've been reading that there's a... less expensive way of calculating distance instead of Vector3.Distance?
i know its not a default emthod in the class so i'd like to know the formula so i can use it during the AI Job
wat like regular - ?
nah, as in a float distance
(a-b).magnitude
i'm... positive magnitude just square roots the sqr magnitude value
then again, i'd better just use distance and worry about optimmization later
i apply rb.AddRelativeForce (500, 0, 0, ForceMode.Impulse); to an enemy, but the strength of the add force is depending on the frame rate, but i only call it once and not in update/fixed update, how can i fix that?
You are right. When you are simply comparing magnitudes, you may as well use sqrMagnitude. It skips the single square root operation. It is a simple optimization that is very worth it when in a "hot path" (like evaluating distance every frame across a hundred units or something haha) but distance is fine for the player
Impulse mode directly modifies the velocity value by the force (newtons/meter) divided by mass all at once. It is not affected by frame rate. So I'm not sure what is going on. Show more of the code?
nope it's affected by frame rate
i changed the frame rate in code and it changes how strong it is
I mean.. it is not normally. So you are doing something else. It is how impulse mode works. It is not affected by frame rate.
How is normal movement handled?
it's a nav mesh agent
Do you disable the agent before doing addforce?
The navmesh agent will continue trying to affect position while addforce is going.
Try it
but this has nothing to do with the force being different when changing the frame rate
The issue still happens when you disable the agent?
This is a good chart
hmm i think yes, but it kinda breaks everything disabling it and idk how to code it so it reactivate when it finished moving after the add force
Use a coroutine and a knockback time. Start coroutine, disable agent, addforce, yield wait, reenable agent.
You don't really need the full force to act, a time flying might even be better
yeah ok it works :)
i actually thought of that but i was like "surely that's not the best/most professional way to do this" xD
is a delagate like a void* but for multiple functions?
Its similar to a function pointer, doesnt have to be void, and can have multiple functions but that's a benefit, not a requirement
Will Camera.main always have the right camera in the context of OnMouseDown()?
I wouldn't expect anything weird to happen.
Camera.main is just the first camera that is found with the MainCamera tag. if you have multiple cameras in the scene with that tag, it will not change dynamically based on what camera is being used. it will still just be the first one found
I see. Do you know of a better way to know where a given collider was clicked?
It feels weird that OnMouseDown() doesn't provide that information when it definitely has it
(unless it does and I'm missing it somehow)
use a raycast or the event system interfaces
Did you try to do a raycast with Camera.main.ScreenPointToRay and have problems?
that doesn't avoid the issue of using Camera.main unfortunately
i would still need to do that through the camera likely
unity knows which camera it's using and it knows where im clicking but opts not to tell me
you have not actually specified any issue with it yet
i dont want my code to break just because i change a tag on my camera
how could unity know what camera you are using if you have more than one in the scene? you have to tell it which one you are using
thats the issue im trying to solve
it's providing me the hook, not the other way around
what do you mean by that?
if it knows something was clicked, then it must know which camera it used to know that
unity should be telling me which camera was used to know that something is being clicked
OnMouseDown doesn't provide any information.
hence my problem lol
could you walk me through how you would raycast?
itll highlight why that approach wouldn't solve my issue
why don't you actually describe what it is you are actually trying to accomplish instead of making me play games to get any useful info out of you? what good would it do for me to explain how to raycast if that isn't even going to be a useful solution?
https://xyproblem.info
this doesn't feel like a constructive conversation
i feel like ive been clear about the problem im trying to solve
problem: i want to know where the user clicked from within my OnMouseDown hook. i dont want to use Camera.main to achieve this
and instead of using OnMouseDown you could raycast from the mouse's position to get the object it is clicking on as well as where it clicked. or you could use the event system interfaces like IPointerClickHandler or IPointerDownHandler which conveniently provide PointerEventData
ideally though, you would also only have one MainCamera in the scene
i apologize, that was the answer i was looking for and you were right that the way i was asking was stopping us from reaching that
i agree with this, but i also dont like the idea of "main camera" in general
using tags is flimsy
but the event system approach allows me to have control by only putting the raycaster on the camera i want it on
okay, then don't use tags or Camera.main and just track what camera you are using yourself. you should still ideally only have the one main camera in use though
and gives me the position information
thanks i got something working that im happy with
eventData.pointerPressRaycast.worldPosition is what i was looking for
from within OnPointerClick
I'm firing bullets from a firepoint at the front of a barrel. No matter what i do, the bullets fly 90 degrees to the left. This is the current situation but i've tried many configurations: GameObject newBullet = Instantiate(bulletPrefab, firePoint.transform.position, firePoint.transform.rotation);
Rigidbody rb = newBullet.GetComponent<Rigidbody>();
rb.AddForce(firePoint.transform.forward * bulletForce, ForceMode.Impulse);
perhaps firePoint is just wrongly oriented
I've triple, quadrouple checked if the forward directions and rotations all line up, yet they keep flying directly to the left, even hardcoding a rotation
select it in the scene view and make sure you're in Pivot + Local mode
ensure that the blue arrow points forward
if you have the scene view on Global, not Local, you'll see the orientations
Hello does somebody know how to change this
TO This
Code i use ```java
Vector3 DirToTarget = Vector3.Normalize(Target.transform.position - transform.position);
float DOT_Prodct = Vector3.Dot(transform.right, DirToTarget);
i assume that i need change this line "transform.right" but don't know to what
Thx in advance
it usually helps to explain what you are expecting to change. also see #854851968446365696 for what to include when asking for help
are you trying to get a vector that points to a target?
are you asking me?
Yes. I don't know what you want to do.
I don't know what these "0.5" and "-0.5" values mean.
I'm noticing now that the blue arrow does not rotate along with my gun, but even then it does not make sense that without fail the bullets fly 90 degrees to the left of the barrel
You are in Global mode.
Toggle this to Local.
(The UI might look different in older editors. Hitting X should toggle it either way)
You will find that the blue arrow points to the left
Yeah so the blue arrow does indeed point directly at the enemies but still the bullet flies to the left
I have an object whoms orbit I want to fake: I have the orbit period (in seconds), and I want to continuously (in fixed update) update and store the current position (for saves), but I don't know how to get that. My first thought was to use a timer that increments 0.02 every fixed update, but I don't know if a very large float can even be added with a very small float (the orbit period would be pretty long)
edit: Could I use a long (long int) counter that counts up every fixed update, then divide that by 50 (fixed update frequency), then do counter / orbitPeriod? Imma try it out
edit(again): it actually seems to work
Check that firePoint is assigned correctly. Also, make sure you aren't just hitting a collider and getting deflected.
(maybe disable the projectile's collider)
this assumes that it's non-kinematic, of course. If it's kinematic with a component moving it manually, then that's another problem entirely
omg thank you, this solved it
Ooo, at moment i am using this code
DOT_Prodct = Vector3.Dot(transform.right, DirToTarget);
in this instance (Image 1 ) DOT_Prodct's result will = about 0.1 f , it's at Left side of car.
and it is finding dot_product according transform.right.
but i need to find dot_product according not transform.right - but transform Looked at PINK object like in Image 2 so
DOT_Prodct's result should be = about - 0.2 f ,
to get a vector pointing from A to B, just compute B - A
so, (known.transform.position - transform.position).normalized
2 minute, i'll try
like this
private void OnCollisionEnter(Collision collision)
{
var emitParams = new ParticleSystem.EmitParams();
+ // IF I USE
- emitParams.position = new Vector3(0, 0, 0);
+ // It will emit particles at "Custom_SimSpace_Transform"it is for example at (257,533,1043)in world postition
+ // So i made this thing bellow
emitParams.position = Custom_SimSpace_Transform.position - collision.contacts[0].point;
+ // But it works not right as shown in video
emitParams.applyShapeToPosition = true;
Emit_1_obj.Emit(emitParams, 30);
}
Correct.
also, if you want an angle, you can use Vector3.Angle or Vector3.SignedAngle
thx very much ,i'll try it in now
Hey so say I have 6k objects
And I need to know which objects have moved/had their transforms changed
Currently what I do is I have to go through each object, check transform.HasChanged, and then do stuff based on that
is there a better/more performant way to do this kind of check?
because this gets pretty bad
what if you stored Transform, not the Component?
oh shit right
maybe along with a Dictionary<Transform, Component>
that has a nonzero cost
It looks like about half of the time is spent in there, yeah
I should really benchmark that. I've tried to minimize transform accesses in the past after noticing that
the other half is List1.GetItem
that will be harder to avoid
yeeee
Do you directly control these objects, or are they getting bumped around by physics?
I do not directly control them
gotcha
if you did, then it'd make sense for the object to add itself to a HashSet of changed transforms
mhmmm
It's possible that get_transform is a lot less impactful when not in deep profile
i.e. that it's only 10% of the runtime, not 50%
yep that is true
but it stacks up
oh yeah that defenitely helped
from 13.6ms to 11.6ms
I wish there was a way to have them combined but not also have that worse performance so I didnt have to have mutliple lists
oh awit ffs I also forgot that having List.Count as a variable in a for loops definition has a cost as it calls it every iteration
so now its time is a mix between transform.getHasChanged and list1.GetItem
wait also also finally
so transforms have a haschanged
is there anything like that for lights?
cuz otherwise ive got this mess where I have to check and update every light
A better way is to simply mark those objects somehow (maybe throw them in a dirtyObjects collection) when you move them.
rather than iterating over all of them
but I dont know what has moved
I aint the one moving them
not up to me
making something for others to use
so its up to them how or when or why they move
could be physics, could be other peopls scripts, etc.
You can't reliably use Transform.hasChanged.
You don't know if a user is also trying to use that for something
and then you will compete with them
everything works perfect ,another question i believe last one- with new code it is works like transform.forward is it possible to change it ,so it would work like transform.right. if Target at front or back result = 0 and if at right side it would be 1 or -1 ?
The simplest way would be to rotate the vector by 90 degrees
Quaternion.AngleAxis(90, transform.up) * oldVector
assuming that transform.up points out of the screen here
ah, it does; I can see the gizmo cube in the top right
anything for this? What can i do about lights and transforms then?
how does unity handle updating light info on the GPU?
what are you trying to do?
not "check if things have moved and update the lights"
explain the gameplay you are creating
I aint creating gameplay
I am creating a renderer thingy, and for that I need to know what transforms have changed so I can update the appropriate bounding boxes on my side, and same thing for unity default lights, I need to know which ones have changed so I can update my GPU side version of those lights to the new values
If I have an object with a tiled sprite renderer, and I want to scale it (like to 1:3 from 1:1), how do I make it so it doesn't render as 1 very wide object, but like the whole area is being sliced to the new area?
I inquire about this because I assume unity already makes a list of lights on the GPU from the ones on the CPU efficiently, which must mean they aint re-combining the entire list and sending it off every frame
What I am getting is: if I used a sliced sprite set to 1x1, and then scale it by 3:1, it's just the same image with every pixel made 3x wider
If I make the sprite renderer have a width of 3, then know the whole thing is 1x9, with every pixel 3x wider
and if I don't use scale, then I'd need to figure out how to scale every individual component individually, and make sure nothing breaks -.-
Anyone know how long the delay is after SetActive(false)?
I have a script that sets a GO to inactive, then reactivates it within like 1 frame and it's not actually restarting it. As in, the Start lifecycle doesn't restart on it
I'm considering adding in some forced time delay with a coroutine, but i was wondering if maybe there's a better solution
there is no delay
SetActive is immediate
Start is never expected to run more than once per object, no matter how many times you activate and deactivate it
You should look into OnEnable which will run every time it is enabled
oh weird, so then I have a follow up question cuz I assumed that disabling it restarted the hook,
if a scene reloads & this GO is a Singleton instance, i am observing the Start looping again
Start will run on the new copy in the scene that is loaded
it will not run again on a DDOL copy that is leftover from the earlier scene
It is an entirely new object then
here's my singleton code,
you're saying that the new object gets made, and replaces the existing one?
no
the new object gets made
and destroys itself
and leaves the existing one alone
that's what line 17-21 are doing
oh right cuz it skips 23 if it enters that conditional
ok so that is what i wanted, but i'm still observing the Start of the existing one firing again... hmm
doubt that very much
or something that appears that way
you can prove it with this:
Debug.Log($"Start is running on instance {GetInstanceID()}");```
put that inside Start
if you see it twice with the same number, I will believe you
ok i'll try it out!
oh you know what, idk if i actually ever tested that case! now that I think of it
you must be right
as you usually are 😛
i'll try the OnEnable like you mentioned instead
Does OnEnable qualify in the same condition as Start as well?
As in, could I move my Start code into OnEnable and it would cover that condition as well as the SetActive condition?
OnEnable runs any time the script is enabled
this happens:
- when it's first created (assuming it's active from the start)
- whenever it's enabled or the object it's attached to is activated
ok i think it should work for my case then i'll try it out ty 🙂
yep, it worked
thanks again!!
Anyone have any idea how I can add a composite outline to a set of tiles? It should look like the composite box collider, but not a collider of course, and the outline would be visible during runtime
You could use a LineRenderer and build the points from:
https://docs.unity3d.com/ScriptReference/CompositeCollider2D-pathCount.html
https://docs.unity3d.com/ScriptReference/CompositeCollider2D.GetPathPointCount.html
https://docs.unity3d.com/ScriptReference/CompositeCollider2D.GetPath.html
Thanks! gonna check it out
I'm running into a case where it appears that a Singleton is not found on Start() for a non singleton when a new scene is loaded.
GameObject.Find("MainManager") is returning null
are you assigning the singleton in Awake?
no, in Start
move it to Awake
btw if you have a singleton why not make it static and use that instead of GameObject.Find("MainManager")
true, I should be referencing the instance member of it
I'll fix that too, thanks
There is no reason to use GameObject.Find for a singleton
you should have an instance reference you use directly
yup! i changed it
Is using Awake also recommended for dynamically loading any Resources into a GO on it's instantiation?
I am noticing a similar type of behavior for resource loading where there appears to be a race condition. Sometimes I get a resource loaded when doing it in Start, other times I don't
hmm I don't use the Resources class, I would assume so. I can't tell you exactly for sure, I would double check the sequence of events maybe, you can mess with Script execution order but really that a last resort
Yeah i've sorta made an anti-pattern in my resource loading.
I need to refactor and think of a better way. Currently I have a BattleEnemyManager that gets the groups of enemy names for a particular battle from a Singleton, it then loads a Prefab, Animator Controller, and SOs for those enemies and attaches them to an EnemyScript that uses all of them. However, because those are attached at run-time after the EnemyScript is instantiated, there are race conditions...
I'm not sure what a better approach is when you are making procedural battles?
I think I'm loading too many separate resources, for instance I try to load a set of actions for the enemy in Resources which is totally uncecessary. I should remove that completely, put those Actions into the SO I am loading in instead
Does anybody have a good example of a well organized modular weapon system or know where I can find one? I'm working on a weapon system that includes both hit scan and projectile based weapons and it's working fine but there are a few things that could be better structured with regards to the weapons that fire projectiles.
Yeah i was thinking if you're using SO why not use those instead
yep I moved them into the SO and I think it fixed that particular race condition
avoiding Resource loading as much as possible seems like a generally smart practice
Afaik it is
Is there any way to reference a class with a serialize field? Not a class instance but a class itself.
I have a base class with a bunch of derived classes, Need to be able to pick one of these derived classes in a ScriptableObject
Hello everyone , I have this switch statement and I'm using it for voice recognition , Does anyone have any ideas that I could make it scale better? (making it work with a larger amount of keywords/phrases I can access) Like loading text into a struck or something
switch (arg0)
{
case "jump":
animator.SetTrigger(arg0);
recordingCanvas.resultText.text = arg0;
break;
case "second jump":
animator.SetTrigger(arg0);
recordingCanvas.resultText.text = arg0;
break;
case "hello":
recordingCanvas.resultText.text = arg0;
StartCoroutine(nameof(ToggleSpeechBubble));
virtualAnimalSpeechBubble.text = $"Well hello there";
break;
case "good morning":
recordingCanvas.resultText.text = arg0;
StartCoroutine(nameof(ToggleSpeechBubble));
virtualAnimalSpeechBubble.text = $"Good morning to you too!";
break;
case "good afternoon":
recordingCanvas.resultText.text = arg0;
StartCoroutine(nameof(ToggleSpeechBubble));
virtualAnimalSpeechBubble.text = $"Good afternoon";
break;
case "where are we":
recordingCanvas.resultText.text = arg0;
StartCoroutine(nameof(ToggleSpeechBubble));
virtualAnimalSpeechBubble.text = $"Family Farm & Home!!";
break;
default:
break;
}
i know that i can multiply a quaternion by a vector to basically "rotate" the vector, how could i do the oposite? like... idk, ""divide"" the quaternion by a vector
dang it, it keeps crashing on me :<
yeah looking at the reference it should
thanks
np
Dictionary ? or like some type of database?
bumping this ^^
either , that would allow me to have a bunch of words/phrases to listen for , I know for sinlge words I could use a list but not sure if it'll be good for phrases
you could probably use them as actual query depending on what accuracy you want , you can also experiment with Vector based DB
ok I'll look into the Vector based database
basically how language models interact with inputs , think like machine learning
Dictionary with a mapping of word -> phrase seems like the most obvious answer:
{
"hello": "Well hello there",
"good morning": "Good morning to you too!",
...
}
this is in json notation would need to be written in c#
Why use a vector database? That only really make's sense with llms to query information. If you need a specific mapping to each phrase then a dictionary/hash map makes much more sense.
bcuz go big or go home 😛
lmfao
Dict is def good enough, but yeah vector if you want to do a more complex dialogue chatbot thing
you can also just use other types of db that allow phrases as query , object/doc based ones
Yeah that does seem more logical answer...
if you want to reference the class, you'll want to reference the Type. It's not serializable by default in Unity but you could write your own serialization for it or look online for one. Storing the fully qualified name will essentially give what you need.
Alternatively, you could use MonoScript which is the type that represents a C# script file. It has a few handy helper methods, including one that will get the Type.
https://docs.unity3d.com/ScriptReference/MonoScript.html
i'm having an issue with what i could describe as transforming points from local to world.
Down below is a picture with 4 points, enumerated from 0 to 4, these points are not Transforms, but instead local positions relative to the game object's position stored in a ScriptableObject (this later gets deserialized into structs for usage with a job)
So far i've managed to easily transform the points from local to world, since the Transform component has such capabilities (mainly Transform.TransformPoint for Local->World, and Transform.InverseTransformPoint for World->Local). so scaling the game object and moving it around the points change accordingly
the issue i'm having currently is when i rotate the object, by default, rotating the game object does not rotate the points accordingly, i know this is an easy fix, since i can just multiply the GameObject's rotation by the point to get the rotated point.
However, doing this is yielding me bizarre results, below is another picture of what my attempt at rotating these points yields, notice the fact that i'm rotating 45° on the Y axis, yet the resulting translation appears to be a rotation of 90°
Here's the code i'm using for transforming the points from world, to local, removing the calls to TransformPoint and InverseTransformPoint give me the expected rotation results, but of course, that means that the points arent properly transformed when the game object changes size or position
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Thanks for the info, looked into it, probably gonna end up just storing a string with the class name and use reflection.
@stark ginkgo what about adding things like setting animation triggers and calling methods?
( I replied to my original post to show what I mean )
I created the dictionary in it's own class (Image)
and use it like this in another class
if (voiceCommandDictionary.keyPhrases.TryGetValue(spkoenString, out string value))
{
recordingCanvas.resultText.text = spkoenString;
StartCoroutine(nameof(ToggleSpeechBubble));
virtualAnimalSpeechBubble.text = $"{value}";
}
You can make a dictionary between the word/sentence and an all encompassing class like:
class Action
{
public bool respondsWithMessage, (if this is false, then call the callback method, if this is true just do the default response with the message variable)
public string response message,
public virtual void CallBack,
}
i've managed to make this work by doing this
if(_transform)
{
localPos = _transform.rotation * localPos;
localPos = _transform.TransformPoint(localPos);
localPos = Quaternion.Inverse(_transform.rotation) * localPos;
return localPos;
}```
I dont quite understand how it works, but now rotations are properly applied to the points
Could you elaborate on this a bit more?
I mightve misunderstood your question, do you want each sentence to have their own function be run depending on the sentence, or would each sentence go through the same functions
Getting a key , method pair basically
Some keys will have a string value others will have a method value , or a value like animator.SetTrigger()
I haven't actually encountered this in c# as im more of a js person, but found something that should work:
This is a dictionary between a string, and a function that takes a string as an input and returns a bool
var dict = Dictionary<string, Func<string, bool>>
Then you can just have:
dict["hi"] = hiFunction;
where hiFunction is defined as:
bool hiFunction(string) {
print("hello");
return true;
}
Or you can also use an inline function, this is more popular in js:
dict["bye"] = parameter (string) => if (parameter == "string") return true;
They dont need to return anything or take any parameters either you can set them to void
Thank you , I will try this
This is interesting, I never thought about storing functions in an actual dictionary...
I wonder if this would be a good way of doing console commands? 
Thinkin about how you handle params that differ...
@tawny mountain I'd do something similar, but instead I'd just make it event based.
Would it be better using generics with an abstract "Command" class that it inherits from and then just have an "Execute()" function with different params? Then they can just override the one that takes the correct params?
lmao, im tired, this is actually nearly identical to what i would do. I would just use Action rather than Func. Ignore me 🙂 @tawny mountain
Because you could then have a single file/class to store all the stuff you need, and then just do a dict lookup and invoke, and you don't ever need to return anything it looks like, hence Action.
appreciate it lad
Hello. I am trying to find a way to display gizmos in the game view for a VR game I am making. or at least a work around. I currently have exactly what I want showing at runtime in the scene view but cant see it in the game view which is what goes to my headset.
Gizmos are editor-only. If you want them to appear in a build you need to use a 3rd party package like Shapes, or draw the lines yourself
cool I will look into shapes. Been trying to avoid drawing the lines myself as I would like them to be more like meshes
nvm shapes is 100$
is there an option to get more than a wireframe with drawing the lines?
There are no options with Gizmos, no
oh I meant with drawing the lines myself. It seems like that would only be able to produce a wire mesh.
Depending what you need, using a Line Renderer may do the job
but it's generally best for quite simple things
hmm I want to render about 100 boxes according to tracking positions, visualizing the shape is very important for what I am doing as I am trying to implement basic gestures from scratch.
If they're the same size, you can model it. If they're not, you'd have to use shaders to make it resizable without deforming oddly.
If they're not scaling dynamically, line renderers may also do the job, you would have to test whether you can make an adequate box with them though
forgive me I am not sure what you mean by "model it" the boxes would all be the same size but the size can be changed by a parameter in the editor at the moment. Could you elaborate on that?
I mean modelling it in a modelling program like blender
what would I be modeling?
A suitable box with the wireframe thickness you want
hmm I mean I tried using primative game object cubes but I wasnt able to instanciate them fast enough
i feel obligated to tell the person who taught me something i felt a wrinkle form in my brain while i did some research on that. i have been enlightened and i am now thinking in three dimensions. thanks again for the info
5D chess moves coming soon
big facts
you are not using your parameter Vector3 vector at all
Is there a way to find all objects in an area without using colliders?
In 2D
I need to put them in an array
you can use GameObject.Find() but for some people, this approach is expensive.
I think the best way if you want to generate object, put it in a parent object, and loop through the parent and register to the array 🙂
I'll only have to do it once, so I think it's fine to use find..?
Can it work with positions tho?
There is a better way. Track objects from the start. if it's a rectangular or a circular area - proximity check is trivial. once entered you can add them to a separate list
Hmm
what are you trying to do anyway
You would need some sort of spatial partition data structure
actually you can use find, it's provided by unity. but it's not best practice i think, since find would loop all object in the scene.
also you can get the position via transform. or gameobject.transform.position
I have a rooms system in my game, and I want all the objects in a room be disabled once you leave it
I'm sure there could be a better way to do that, but that's the only thing I could think of
so you want to disable object once it's out of the room without rely on collider2d right?
Have a trigger on the exit and loop trough all the children of the room
You definitely dont need to use find then or any physics overlap functions. Your objects should just be associated to the room like as a child or in some list setup in the inspector. When the player leaves the room (I assume detected by a trigger) then you can disable it from the existing list or child of a object
yup, I think this is the best approach too
Disable parent gameobject will disable children too, unless some go are shared but in this case you cant simply use eg overlap box to do this ie your current approach
Foe this case it most certainly is
Oh I didn't think about it
Seems so obvious now lol
Thanks!
do you plan to change to other rooms once player exit the room?
I didn't really get what u mean by that
Like, enabling all the stuff on entering? Yeah!
I already have the camera system set up to work with the rooms
oh. alright. good luck with the game 🙂
Thanks!
what this name has been changed to in unity any one knows
NativeMultiHashMap
in burst
idk what was the need for change of name
• PlasticSCM
• Git: Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory
Hey can anyone help me with a rigidbody problem? I’m new to unity and I’m trying to make my rigidbody physics on my player work in the air so that they can maintain velocity and change the direction without accelerating. I can basically simplify the problem to this: The player is moving with a velocity with 0 drag and 0 friction, so they will just keep going if they don’t press anything. Assume the player already has velocity so they can’t speed up at all, just move around and maintain their current velocity (or stop if they wanted to). If they look in the direction of their velocity and A/D, they should turn, but maintain the same velocity. I also need to do this without manually setting the velocity, because that messes up other stuff, I just want to work with forces. The result should be that if the player is travelling forward, and presses D, they would slowly move right, making a curve until eventually they were travelling right with the same velocity as before.
Not quite sure to understand your problem. Your character walk/run on ground, and after jumping, you want it to keep its velocity and have to input just change the orientation of you character. Is that it ?
I'm trying to work on moving in the air, but you can ignore that, just imagine that it is moving. Like an air hockey game, with 0 friction and 0 drag. @tired elk
Not to change orientation of character but just to be able to move around a bit
The problem is that for the player to move, I need to add forces, and this ends up accelerating the player to a higher velocity. But they should just maintain their velocity. I have tried for 2 days and cant find a way to balance the forces
Well, if you want to move around, you'll have no choice but to alter their velocity
For some reason, this piece of code keeps giving me an error, it is meant to move my player based on wasd, but it doesnt move at all and outputs errors.
A moving object, which maintains its velocity, can't physically move around its initial trajectory
What is line 38 ? You cut the line on the left
No I'm going to change their velocity of course, but I mean I don't want to use rb.velocity =
Because that is bad practice and causes issues in everything else
Last line
Just to use forces
Then add force in the direction you want your character to go
That accelerates them and they go faster.
I'm trying to balance the forces but I can't work it out
then the getcomponent on line 22 has failed
That's true only if the force is in the same direction of your current movement
no, even if it is close
That's more of a math/physic problem than a Unity issue unfortunately
if player is heading north and you add a force east, they will speed up and change direction
I am trying to figure out a nice way to keep track of the amount of Nades, bullets and consumables like health the player has at any given time.
What is most common way of approaching this ?
The way I am thinking is having a Class to keep track of the amounts of item the player has. But If I think about it a little more it seems a little stupid to take that route assuming the player has 2 pistols, 3 rifles, a sniper rifle and 3 different grenades . That will then be 8 x 2 variables so 16. 2 per item. Amount held and stack limit. That is excuding the actual amount of bullets the clip can hold. Then agian I might be overthinking this. Any input would be great
Maybe your force is too strong then
Yeah true. I'm sure other people have had similar issues though as its quite basic, so im looking for help here
Any force will increase their velocity in that scenario
check to make sure the PlayerMovement script is not also on another object
Nope, its only on my player
This is weird. If you don't change the orientation of your system, if you add opposite force lesser than currently applied forces, it should decelerate
How did you implement your solution ?
It isn't always an opposite force. The scenario I was describing was player heading north and they press D to add force east
should look like this
That's just one example scenario though. If they pressed S of course they would slow down and eventually stop
I've seen games have it and it seems like quite a simple setup but for some reason it is so unbelivably difficult for me. I've spent days and tried like 10 different approaches
I have no idea what the issue is
Add a Debug.Log after line 22
if (rb == null) Debug.Log("RB is null",gameObject);
This is what you're trying to achieve then ?
This is what would happen in that scenario, yeah.
If you've ever played the game splitgate, I'm trying to achieve something similar to what they have for movement in air with speed
ye it still doesnt output anything in debug
then your NRE's are gone as well?
No they still are there
Just the debug message isnt showing
Here's the full code again
Ok, move the Debug.Log to before line 38 and try again
show console
if you double click on the message it should take you to the gameobject that generated it
when i double click it takes me to the debu.log code
ok try this one
if (rb == null) Debug.Log($"RB is null in {gameObject.name}",gameObject);
Odd, something somewhere is Destroying your Rigidbody
try this.
Copy the GetComponent to above line 31
Sorry. I'm an idiot.
your GetComponent is wrong
it sohuld be
rb = GetComponent<Rigidbody>();
I'm amazed your IDE did not throw an error
Yea exactly
i didnt even know you could do rb.getcomponent...
Thanks steve, you are a legend
of course, GetComponent can be done on any component. but doing it when that component is null and uninitialized should have thrown an error in your IDE
btw you would be better making rb public and filling it in the Inspector, that way you dont need the GetComponent
@obtuse cape another tip buddy is to call rb = GetComponent in start or awake, this will allow you to cache it and use it whenever rather than calling GetComponent in an update loop which can be taxing 👍
you should have read the complete conversation
@knotty sun just a tip
if you read the conversation, I asked him to copy the line FROM Start to FixedUpdate to test it
That's great
You could of just told him to make it public to make sure it's assigned but hey hoo
I did that as well, if you could be bothered to read
I have an animation with root motion, but i want to remove the root motion and instead move the actual game object with the same distance
I'm currently trying to do this with a timeline by adjusting the distance traveled comparing the same animation, but one with root motion removed
is there a way to get the root of the moving object? the values i use to adjust this always are slightly off
I have a rigidbody3d with mass 45 but after I jump it just slowly descends to the ground even though I didn't touch the gravity value, any idea what I could be doing wrong?
if i remember correctly mass doesnt affect the speed at which an object falls
but collisions between objects
Hmm, if I comment out my movement the jumping works as expected
my movement:
myRigidbody.AddForce(new Vector3(moveDir.x * 60f,0f,0f), ForceMode.Impulse);
my jumping:
myRigidbody.AddForce(new Vector3(0,1f,0) * 1200f, ForceMode.Impulse);
so I guess my movement in fixed update is interfering with it somehow?
i would assume somewhere you are directly setting the velocity
but if not i cant see any issue with that
Okay, I think it is fixed now. I'm not exactly sure what I did though 😅
Do you also happen to know how I can fix my character sliding on the ground when I land and I am not setting the velocity directly?
Increasing the drag on the character also makes it harder for them to jump and move
I set the physics material of the ground with both friction values 1 and it still feels like I am on ice
Hi, sorry for the ping, I had the same problem and just wanted to thank you, it solved it!! (Doing that test in both callback side, for others in the same troubles)
i think the quickest solution would be to set velocity to zero, or slow the character down when you land
you mean that after you jump/ fall down somewhere you arent applying any more motion right?
Hey, when I add a terrain to a gameobject like so: var terrain = island.AddComponent<UnityEngine.Terrain>(); and apply a terrain material and an alphamap, it works but the normals for the terrain layers don't show until I re-select the material in the inspector manually and I can't figure out why.
there should be a little bit of sliding but not as much as I have now
if the answer to my question is yes, then i assume that the player doesnt lose the velocity of the x and z values when landing
only the y value is cancelled out
Oh, I figured it out.
If you reset the rotation of the object, the physics in unity seem to get confused
I now froze all rotations of the character and there is no more sliding
Now I just need to figure out on my own how I can make my character still spin in the air
Can you like freeze and unfreeze specific axises in script?
like the constraints of the rigidbody?
yes
yes you can
hello! I have a little issue with a script for an AR project, is there specific channel where i can get some help ?
cool thanks a lot
If it's specific for AR, ask there. They do script help too of course. But if it's general, ask here
perfect thank you !
does anyone know?
Hi, im trying to make something that when I add a gameobject to an array in edit mode a button gets created for it ingame. is this possible? and how would i accomplish that?
I do something like that frequently
Make a monobehaviour with a [SerializeField] private GameObject[],
and also make a prefab for the button object (so it has all the other knickknacks like the picture/text/scripts/etc
No idea. May wanna try asking here
https://discord.com/channels/489222168727519232/497875195718271004
ok
OnStart(), call a function that goes through all the gameobject array, instantiate the button prefab for it, and set the button prefab as a child of the target object on canvas where you want to house them.
The target object on the canvas should have a HorizontalLayoutGroup/VerticalLayoutGroup/GridLayoutGroup component to help make them not look shitty together, automatically.
Then, in the newly instantiated button gameobject, we need to GetComponent, to go grab either a monobehaviour component in the prefab (to help us modify the prefab easily), or just GetComponent<Button>() so we can .onClick.AddListener to tie a function to it.
make sense?
Yes it does very much! thanks :)
A word of advice btw; Keep a list/dictionary/array/etc with references to all the prefab-based objects you instantiated.
The thing that spawned them will likely be a point of contact in case you need to get references to the button prefabs.
Especially if you just want to ask all the buttons to be destroyed/disabled at once
alr thank you for the advice i will keep that in mind
what kind of game are you making?
I want to make something like that old game habbo
but less complex ig
i thin i know the game. like pixel isometric?
is a really old game, like 10 years ago now?
yep thats the game
I can't figure out how to connect the correct button to the correct index of the array. I want to spawn an object when I click the button. The button that i click should spawn the object that i have put in the array... how do i do this?
it was a fun game back then tho haha
do you mean you have an array of buttons that spawn gameobjects?
no i have an array of objects
that’s what I thought, so I’m confused by that comment
the button gets spawned
so clicking the button can’t spawn the button, because it’s already spawned
Null-coalescing operators always check for reference equality and hence the discrepancy in their outcomes. For a destroyed GameObject, the reference equals null even though its actual value is not null.
so no ?? operator in unity?? 😦
no
I add my objects to an array, and when i start the game i instantiate the same number of buttons as the length of the array with my objects. when i click one of the instantiated buttons it should spawn the right object from the array
you get what i mean?
i get you. The button should not be accessing that array
the button spawner should be using GetComponent() on the new button’s gameobject to search for a monobehaviour that you made. This monobehaviour should have a public function so that the button-spawner can give it the information of what gameobject it is tied to
the button-spawner’s one responsibility is to spawn the buttons (and maybe re/despawn them). The button needs a script whose responsibility it is to do anything specific to what happens when the button is pressed.
Button spawner just needs to give the button handler the info of what it is tied to.
sure
You can use it all you want, it's just gonna behave wonky for GameObjects. You can use it for C# things like lists, POCO data objects, and other non-Unity things
My game has a lot of objects spawning/despawning/respawning. I’m thinking about changing from an object destruction strategy to object pooling method. For this, I’m contemplating making an IResettable interface so I can reset variables in components as though they are new. Is this a good idea, or is there a smarter way?
iirc works for Coroutine as well ?
Yeah, as long as it isn't a UnityEngine.Object
well i wanted to use it for unity's monos
u think they will make it work in the future
doubtful. the reason it doesn't work is because c# doesn't really have the concept of "destroyed" and unity have overloaded the == operator to check if a UnityEngine.Object has been destroyed. the null coalescing operator does not use the overloaded operators so it cannot check if the object has been destroyed
so using that operator with unityengine.objects can lead to MissingReferenceExceptions and other similar "your object has been destroyed but you are still trying to use it" exceptions
indeed -- your GameObject variable doesn't literally become null when the game object is destroyed
It's just convenient to make it look like it does. "I don't even have a reference" and "I have a reference, but it's to something that was destroyed" are often handled in the same way.
not really a coding question...
because its in orthographic mode,
dont crosspost , also not a code question
IEnumerator JumpCooldown() // deprecated?
{
onJumpCooldown = true;
yield return new WaitForSeconds(.5F);
onJumpCooldown = false;
}
async Awaitable JumpCooldown()
{
onJumpCooldown = true;
await Awaitable.WaitForSecondsAsync(.5F, destroyCancellationToken);
onJumpCooldown = false;
}
```Hey I have a question about Unity 2023, are coroutines being replaced or removed and should I move on with async and await?  Anyone familiar? 
Will JsonUtility serialize a private field with [SerializeField] attribute?
Of course
So for what was Awaitable class invented at all?
Huh?
It was introduced to improve unitys async/await support
alright, but method names seem to be equivalent for coroutines, idk...
because unity doesnt cleanup async Task properly
I see it as async/await but with coroutine functionality
Like waiting for the next frame etc.
There haven't been any announcements about removing coroutines, you can assume they will continue to exist forever
Unity rarely removes things
Yep...
Alright, but still, seems it's some replacement for coroutines
not really. coroutines remain extremely useful for doing work on the main thread in little increments.
Doesn't look like it supports many coroutine features
What is missing?
this might clear it up a bit for you
https://youtu.be/X9Dtb_4os1o
In this follow-up video, we explore the Awaitable class introduced in Unity 2023.1, which aims to improve asynchronous programming workflows.
See part 1: https://youtu.be/WY-mk-ZGAq8
Topics Covered:
- Learn about the new Awaitable.WaitForSecondsAsync, NextFrameAsync, EndOfFrameAsync & FixedUpdateAsync.
- Learn about cancellation tokens and s...
Mhm
there are these 2 methods
That's how I found out about it, I even left a comment a week ago 😆
it effectively can be - you can do everything and more with the new async/await support, or the third-party UniTask before 2023
Ohh didn't see that lmao
140 comments, would be surprising if you saw my comment. Anyway, thanks for your help 
Alright, I've upgraded to 2023 already 
it might take some time for the intuition to form on how async/await works, and might seem redundant for people who have already spent the time learning the intricacies of coroutines, but it's a cleaner way of doing things and much more in line with .NET standards outside of Unity (imo)
I will have to break into that eventually.
I've used async/await lately but it lacks the functionality of waiting in Unity-time instead just realtime
Might need to look at 2023 for awaitable then
Or maybe unitask?
from what I can tell the 2023 awaitable implementation is effectively what UniTask has been doing for a while
Before Unity I used to create simple desktop apps using Windows Forms, I am probably more familiar with async/await rather than coroutines 😄
Yeah they look very similiar. Might stick to 2021 for this project and try UniTask
UniTask synch context is based on the unity lifecycle, it has all of the nice things like gameobject cancellation tokens on destroy, etc
Any downsides you can think of?
hell yea Winforms is crap without async xD
Yep but what I said I've been using async/await a lot so it's nothing new for me
But it seems to be new in Unity
it's a struggle using it in a team that is fond of coroutines and doesn't want to learn something new and it can make a mess of callstacks with lots of nested tasks
its not new per-se , it just wasn't implemented like it was for native .net
unity has async void Start for example
generally using void in async is considered bad
https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void
the main thing I like about coroutines is that they are really easy to set to wait for specific parts of a frame. tied to different parts of unity’s execution order
Have you used UniTask on editor scripts? I use a lot of async/await in the editor (for proc gen etc.), does it work just as well?
given the clusterfuck of Unity’s new business model, it is a great time to learn async
Actually UniTask might be redundant in edit mode since there is no need to hook up to unity's cycles (Update, FixedUpdate...)
Yeah, I know, I'm familiar with System.Threading.Tasks.Task class and why async void is bad 
I just posted link in my edit
I haven't tried it, I think there is support but not something I've looked into much
Alright
Hey I am trying to get some basics down for player controls. I am trying to get the player to be able to move foward and backwards, while also rotating witht he camera (in first person) also moving with the player
However I am having some trouble as the player doesnt move on inputs or rotate, and as soon as I set speed it flys off the platform
show script
doesn’t rotating right mean you rotate your front to up?
yeah you need Vector3.up iirc
I want it to turn left and right for rotate but Idk if I did that right
if its 3D you have to be rotating on the Y axis
Oh ok thanks
hi
also what you mean "it flies off"
right hand rule
rotation on X means X axis stays still as the yz-plane rotates around it
Like as soon as I hit play the player goes flying off
that doesn't explain what "flying off" means
horizontal input is not an input
how do I instantiate something when a particle system gets destroyed
you aren’t translating by it
like at each particles position
I think there is a field for that
really?
The cube on the left is the player and as soon as I hit play its like it hits something and starts tumbling off and flys away
transform.Translate would need the input multiplied by vertical input or something
right now, you are programming a straight translation forever
also Translate = No Collisions / Gravity
also, you should probably lock the XY rotation of your gameobject
Oh ok
do u want ot move your player with input right ?
Yes
Translate teleports you onto the target destination
I cant find it
there is a checkbox in rigidbody (i think) for constraints, to freeze rotation. You want to block rotation on x/y
so a Input.getAxis("Vertical")?
so you can only rotate along Z (which makes you turn left/right) in thr plane
yes
yee
vertical is the W/S key
Ah Ok I think I am getting it then
yah I get that but how do I spawn something at each place a particle was
and up/down arrow keys
and that
like even if the particle system hasnt ended
Ohh each particle..hmm maybe you can use OnParticleCollision callback on each one
store their position or spawn it then when it collide
this should help you understand rotation
rotation is done like this because it makes math with vectors immensely easier
So what would I replace in the transform part for vertical input?
what if they dont collide with nothing?
GetComponent<RigidBody>()
iirc unity is left handed
then take that rigidbody, and .MovePosition
that is cancer
right
but w/e
Sub emitters with destroy mode IIRC
u can also use this way i find moree friendly
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}
anyway
Rigidbody RB = GetComponent<RigidBody>();
RB.MovePosition(vectorForNewPosition);
arent sub emitters only for other particles or something? also what is IIRC mode
I know its probably still wrong
I need to change forward don't I
no you just add *verticatInput
Ah
Oh you want to spawn a prefab on the particles?
IIRC just means if i remember correctly
MovePosition moves your rigidbody and checks collision as it goes from A to B
oh ok, yah I wanted to spawn a prefab
Translate is a straight teleport
I dont think there is a callback for when a particle dies 🤔
is this it ?
#archived-code-general message
do you understand, mr raptor?
ahh you mean individual particles
This is why I write my own particle controller so I don't have to deal with unity's spiderweb API
Ok so It does now take foward inputs thank you!
Yeah I think they need to detect single particle deaths
thats for the whole particle system
Still flies away but only when I press foward lol
yup
yea
and their positions
there isent
is there not a single way to handle it?
looking at API but not seeing individual particles
but has to be somewhere, I mean you can get OnCollision on each one, why not other stuff like pos/lifetime
yah exactly my thoughts
You can probably get all particles and check their remainingLifeTime
It sounds a bit hacky
what about their pos?
is this correct to get the player to rotate left or right?
transform.Rotate(Vector3.up * Time.deltaTime * speed * horizontalInput);
is it not working ?
would I need to use a foreach to cycle thru each particle?
how would I cycle thru them
no
what is the matter
also I still dont see a ParticlePos
It gives you an array of Particles. Each particle has a position
Maybe read the doc I linked
what is currently happening? check inspector are numbers moving ?
Also It does collide with the other cubes but bounces off them and flies away
show inspector for this object
oh I see it thank you :)
Again, keep in mind that this is pretty hacky because you would have to detect that the particle is about to die, while it is still alive
Just based on remainingLifeTime it will be error-prone since it might live 0 frames or it might live 2 more frames
remove the rigidbody @silk edge
use character controller
switch Translate to Move
box collider also not needed
is lifetime measured in seconds? also is this heavy and bad for optimization?
so transform.Move?
rigidbody.MovePostion
Just read the doc.
no you have to reference character controller
Oh Ok
character controller if you are using that
public CharacterController cc
cc.Move(etc..
What is the final effect here? Like what are you trying to do
And how many particles
blood
yeah but what about after
don’t make these things public. just private and getcomponent
if your game gets big, you’ll have so many goddamn boxes to fil
nah dont use get component
what I was doing before was when an enemy was shot it spawned a bit of blood nearby
you should use SerializeField
but its better if I use particles
Blood drops that spawn blood splatters, or what?
GetComponent is slow
yah exactly
yo guys does anyone how can i make my itens stack when i pick em up to the inventory?
only when you spam it multiple times a frame
Is this correct?
Is it a 2D game or why you can't use collisions?
it is a 2d game
I mean is just safer and faster to use inspector but agree shouldnt be public but Serialized, but he seems new
didnt wanna explain serializefield llol
top down
yup
i’m just saying don’t serialize it. you know it’s going to be there. Just GetComponent in awake
I was maybe thinking for each particle to
start a coroutine
with the time remaining
and when it reachs the end
it spawns the blood
Oh the PlayerController is not assigned
you have to drag the component inside
the one on your player
No in the script I mean
or it doesn't know which one to use
I dont think theres a way to track a single particle. The array changes all the time so it would change its place in the array constantly
yes you have to assign it inside the Field on the script
where you change the speed, there should be another field under it
There's always VFXGraph, maybe it can support this
Neveremind I see what you mean!
I wont use a emitter over time
I'll just do it in burst
there are 2 ways to assign variables in unity. One is via C# code, where you manually tell it x = whatever. And then you have Unity Inspector, where if a field is serialized, then in the unity editor, you can drag it to a little box for the variable
Yeah but some particles die earlier than others, right?
Maybe it can work if they all have the same lifetime, but idk, hacky as hell
thats why when they spawn I should for each start a coroutine?
what would your suggestion be
how has no one ever think of doing something like this
it has to be a way
Alright so that fixed the major problems of it flying off. It now moves foward and backwards, thank you! Now do I do cc.Rotate for the rotate part>
I would look at VFXGraph 🤷♂️
Or render the blood drops with some custom rendering code (DrawMeshInstanced etc.) and do the logic yourself
Cc doesn't have rotate, you can just rotate the same way with transform @silk edge
that sounds pretty harsh
I'll have to look into it
how much blood are you rendering
Ok so stick with transform.Rotate?
yup
hi i am pretty beginner to unity and networking in general,
i use mirror and i would know how to do a variable in network that all client receive
use mirror's discord
Ok it does rotate my bad, just really slowly
not a lot, I delete it per room like 10 to 50 prefabs per room
man ur a beginner you're gonna be in a world of hurt. Dont' start off with Mutlipayer
ok i didn't know there was a discord for mirror ty
you need to proivde a multiplayer for rotation speed
just like you have speed for movement
One more thing I can think of, is to use particle collisions with a 3D plane collider on the floor that the blood hits
no i don't have really many problem i already coded in other languages so c# is not really difficult
i just need to learn things
Just do an object pool and make yourself a controller if you want full control of it all.
what did you code in what language?
Yeah i am adding turnSpeed = 5.0f then adjust till it works
(You would need to use a Z axis gravity for the particles since it is 2D, not Y axis)
i use python.
I coded In many languages, but mostly Hello World
python isn't really like c# but alr.
Networking in unity isn't easy, best of luck
that might be an idea
can u elaborate?
It will probably solve it for you
ik but when you have basic of programmation it's not pain
you are right about networking
really ? because there is a reason a lt of expereinced coders here don't recommend it until you've done quite a few single players first
even with programming knowledge networking is a pain
i already made a thing in single player
to learn basic
you are right (:
i am suffering
lol
ya
networking makes everything hurt
Pool of GOs with colliders and collision events
like a fully polished single player thats on store ?
lol
I tried making my own blood drops
but it wasnt flexible
not really basic character, i followed brackey tutorial. I didn't copy all, i learn with his video so i make system myself, alone
and it didnt look good
make it flexiable ;)
it really does make you feel like you know nothing and give up
I did a little prototype game with MOBA-style movement
Getting smooth movement is...hard
You can always use the particle system to render locally to a GO, and handle everything else yourself
thats a single player game you made so far? well..best of luck bro ur a brave one
ty good luck to you too
Yeah! the most annoying part is faking physics when you want to make physics games :
I cannot get proper sync of ball in a physics based Pang multiplayer
hey @heady iris, Re on the [serializedRefrence] label suggestion from monday. When making serializedRefrences, should the parent class be marked that way as well, or just the childeren?
apologies for the ping
Thank you again @rigid island! It rotates and moves around. Now I just need to have it push the blocks off but I think that wont need much scripting
hmmm luckly there is a neat function on Character Controler
this has example code of push rigidbodies with your character controller
ofc you can code it yourself with some raycasts if you want to do maybe a "use" key or "push key"
The classes have to be serializable. You put [SerializeReference] on the field.
(you will also probably have to do add some extra attributes / derive extra interfaces, depending on the library you're using)
using UnityEngine;
using System.Collections.Generic;
public class CraterCreator : MonoBehaviour
{
public Texture2D hMap;
public float mapScaleMultiplier;
void Start()
{
GenerateTerrain();
}
void GenerateTerrain()
{
//Texture2D hMap = Resources.Load("Assets/HeightMaps/halifax.png") as Texture2D;
List<Vector3> verts = new List<Vector3>();
List<int> tris = new List<int>();
int chunkSize = 250;
for (int i = 0; i < chunkSize; i++)
{
for (int j = 0; j < chunkSize; j++)
{
verts.Add(new Vector3(i, hMap.GetPixel(i, j).grayscale * 100, j) * mapScaleMultiplier);
if (i == 0 || j == 0) continue;
tris.Add(chunkSize * i + j);
tris.Add(chunkSize * i + j - 1);
tris.Add(chunkSize * (i - 1) + j - 1);
tris.Add(chunkSize * (i - 1) + j - 1);
tris.Add(chunkSize * (i - 1) + j);
tris.Add(chunkSize * i + j);
}
}
Vector2[] uvs = new Vector2[verts.Count];
for (int i = 0; i < uvs.Length; i++)
{
uvs[i] = new Vector2(verts[i].x, verts[i].z);
}
GameObject plane = new GameObject("ProcPlane");
plane.AddComponent<MeshFilter>();
plane.AddComponent<MeshRenderer>();
Mesh procMesh = new Mesh();
procMesh.vertices = verts.ToArray();
procMesh.uv = uvs;
procMesh.triangles = tris.ToArray();
procMesh.RecalculateNormals();
plane.GetComponent<MeshFilter>().mesh = procMesh;
}
}``` so my Texture2D is my world map height map as a png. What am i doing wrong that its not letting me make the chunk size larger than 250?
So I did run into one more problem, the cc.move only moves the character fowards on the x axis, not where it is facing
correct Vector3.forward is in Worldspace
you can just use transform.forward
transform gives you local
also its Z axis
so Vector3.transform.forward?
no
transform is a variable available in every MonoBehaviour.