#archived-code-general
1 messages Β· Page 71 of 1
a powerful website for storing and sharing text and code snippets. completely free and open source.
complete script
Each Rounds is fired after a certain time gap, until all the rounds are fired. Here the timeBetweenRounds is 1 seconds, so each new FireRound Coroutine should start every 1 second. Now lets look inside the FireRound Coroutine. FireRound Coroutine is responsible for firing bullets after a certain timeBetweenBullets time, until all the bullets are fired. Here each bullet is fired after 0.1 second, so each FireRound Coroutine should end after 0.4 seconds as the number of bullets fired per round is set to 4.
yield return timeBetweenRoundsWaiter; // cached WaitForSecondsRealtime - Minimum wait time
yield return stillFiringBullets;//Wait till done firing```It's still yielding between rounds. It should not be immediately firing differently than you had so before..
Something else has changed etc
Round Started :
------ Bullet Fired -- took 0.1 second
------ Bullet Fired -- took 0.1 second
------ Bullet Fired -- took 0.1 second
------ Bullet Fired -- took 0.1 second
another 0.6 seconds wait
Round Started :
------ Bullet Fired -- took 0.1 second
------ Bullet Fired -- took 0.1 second
------ Bullet Fired -- took 0.1 second
------ Bullet Fired -- took 0.1 second
another 0.6 seconds wait```
Round Started
Bullet Fired 1
Wait for x seconds
Bullet Fired 2
Bullet Fired 3
Bullet Fired 4
Thats the issue from the starting, It shouldn't fire next round immediately
It shouldn't.
but here it does
yield return timeBetweenRoundsWaiter; would prevent it as you originally had it.,
Check your inspector.
Maybe some values default with the amount of changes you've made.
Ok so let me record the insepector and share the script used .
Reminder that the yielding of time is immediate and not after the other coroutine has finished.
does onDrawGizmos work in a StateMachineBehaviour?
If you're wanting to yield 0.6 seconds after the other has finished, you'd yield the start of the other coroutine.
Or yield wait until the other coroutine has finished before yielding to time.
private IEnumerator FireRounds()
{
int roundsFired = 0;
while (roundsFired < maximumNumberOfRounds)
{
Debug.Log("<color=yellow>Round Started</color>");
yield return StartCoroutine(FireBullets());
yield return timeBetweenRoundsWaiter; // cached WaitForSecondsRealtime - extra wait time
roundsFired++;
}
}
private IEnumerator FireBullets()
{
int numberOfBulletsFired = 0;
while (numberOfBulletsFired < numberOfFiresPerRound)
{
Debug.Log("Bullet Fired");
yield return timeBetweenFiresWaiter;
numberOfBulletsFired++;
}
}```
With my original script : https://paste.myst.rs/qf63gi89
a powerful website for storing and sharing text and code snippets. completely free and open source.
It shouldn't be non zero if you've got an index out of range.
Which shouldnt
What's a Structs?
I'm assuming some custom type?
With your edit : https://paste.myst.rs/u5w6kzrg
a powerful website for storing and sharing text and code snippets. completely free and open source.
If it's a List it would be accurate
Structs is a list
I would like to note that this function is being called in a 2d for loop, and it works the first time but not subsequent times
public class Chunk : MonoBehaviour
{
public bool PlayerIn;
public Generation Parent;
public LayerMask Player;
public Coords coords;
public List<GameObject> Structs;
public List<float> Rotations;
public List<GameObject> FreeStandingObjects;//Some Furniture, Entities. (Lock to floor)
public List<GameObject> WallLockedObjects;//Doors, Paintings, Vents. (Lock to walls)
// Start is called before the first frame update
void Start()
{
Rotations.Add(0);
Rotations.Add(90);
Rotations.Add(-90);
Rotations.Add(180);
}
public void SpawnStuff(GameObject Struct)
{
//Place the Layout
var Layout = Instantiate(Struct, transform.position, Quaternion.identity);
//Randomize The Layout's Rotation
Layout.transform.eulerAngles = new Vector3(0, Rotations[Random.Range(0, Rotations.Count)], 0);
}
//Rest of code isnt important
here is Chunk
Show the actual full error message
None of that matters. The index out of range states that there are no elements but you're still trying to access the first element.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Also Instead of try/catch you should just be checking the Count
I am
Doesn't look like it
ayy Praetor You god resident good for you
Start shouldn't be immediate so instantiating the object would have the list at count zero.
Show your logs of it's size being two.
imma try and stagger it
I cant actually easily bcause it uses a param
me being stupid
Debug.Log(ChunkData.Structs.Count);
From this, called the line before the error line
the one after the error line does not call
Yo wtf
I put it back in a new try-catch and it worked
fully
all the generation
try
{
ChunkData.SpawnStuff(ChunkData.Structs[0]);
}
catch (System.Exception)
{
Debug.Log(ChunkData.Structs.Count);
}
how odd
well im going to bed
gnight
I hope you are getting whats teh problem here
does anyone here know how to apply velocity on the local axis
please help
I've been trying to do it for over two months
You can convert local axis to global using TransformDirection and then apply the velocity normally...
hi!
Is there a way to reference a Light2D in a script?
using UnityEngine.Experimental.Rendering.LWRP available here
hmm
2 months?
rb.velocity = rb.transform.rotation * someLocalVel or rb.AddRelativeForce should work
Or yeah what volkner said
Just wondering are job posts allowed here?
!collab
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
thanks
so I'm working on a simple pong clone, and I've realized a problem. When the puck hits the top or bottom of one of the paddles when the paddle is moving, the paddle applies a force to the ball (because the paddles are also dynamic and register a collision). The problem is that I need the paddles to be dynamic to not pass through walls, but I don't want this collision force applied to the ball. How can I make that happen?
making the puck kinematic is not ideal
Are you sure you want to use forces in this scenario? Setting velocity's directly might be a better option. And perhaps making the ball kinematic too.π€
that would work but there's a LOT of physics I'd have to handle doing it that way
Also, you could stop the paddles from passing through the walls manually too.
I'd like to leave as much as possible up to the physics engine if I can
Well, pong isn't the most physically realistic game...π€
And applying forces to colliding object based on objects velocities is one of the basic functions of the physics engine, so you can't just disable it easily.
I'll take your solution and make the physics by hand, but I am curious as to how Box2D handles collisions
I read some stuff on Box2Ds documentation but I couldn't really find anything about how collisions are handled in terms of forces
outside of an impulse applied to overlapped figures
It's simply applying forces based on the paddle velocity, mass and collision normal I think.
like uh. Probably not asking my question accurately
eh whatever. I'll just read the docs more. I'm sure i'll figure it out
I mean, what exactly are you looking for? The source code?
The logic is pretty much how you'd calculate that force in real life I think.
I guess I just have a lot of questions that seem obnoxiously esoteric. Like the Collision.contacts array is "a list of contact points generated by the physics engine", but what even is a contact point? how many contact points lie on an edge of a box collider? just one? is it for each vertex?
what about how much impulse is applied to two colliding dynamic rigidbodies?
https://docs.unity3d.com/ScriptReference/ContactPoint.html that's a contact point
if I want to use Vector2.Reflect, I feel like I need to understand how the contacts array is fulfilled so I can get the normal accurately. Idk
this isn't deep enough, I already know this much
Debug the values, visualise them with rays. Then you can see where they are when you get a collision and infer what that means for you
i need to use async inside a coroutine , and i found out something like IAsyncEnumerator
but i dont want to return a type
A contact point is generated by the physics when it detect intersection between 2 colliders. You'd usually only have one.tgey would usually be on the edge of a collider. The force applied is probably calculated from the relative velocity, mass, collision normal and some other properties(like bounciness).
For reflect you can just use the normal of the collision.
this is from a coroutine, the function awaiting is retrieving a string of jsondata
in this case, is await same as yield return?
Hello, why can't I load custom filetypes in Addressables? I use Texturepacker for my games UI which gives me a multiple sprite mode Sprite and .tps file to read the slicing data. When I try to add this to addressables, it fails
Any solution?
No. It's not the "same", but it would wait untill the result is ready to be returned. Share your loadAvatar method definition.
What is the use of void?._.
It means that the method doesn't return anything. #π»βcode-beginner question btw.
Oopsie-
My bad
hi, i made a custom attribute but im not sure how to use it
using UnityEditor;using UnityEngine;
public class Vector4Attribute : PropertyAttribute {}
[CustomPropertyDrawer(typeof(Vector4Attribute))]
public class Vector4Drawer : PropertyDrawer {
public Vector4 value;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return EditorGUI.GetPropertyHeight(property, label, true); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
value = EditorGUI.Vector4Field(position, label, value); }
}```
the purpose is to rearrange how vec4 are displayed in the inspector
you'd type [Vector4] but since that's already a type, I'd suggest naming it something else like Vector4ArrangerAttribute, so you'd type [Vector4Arranger]
Alright, i'll try that.
alright, i've changed the name, but im getting a similar error regardless
The Attribute needs to be in the runtime assembly, and the drawer needs to be in the editor assembly
so if you have put both under an Editor folder, you won't be able to access that code
oh, so they can't be in the same script file together?
they can be
just surround the attribute with that conditional compilation (idk what called)
#if UNITY_EDITOR
// stuff
#endif
works for me
if they are, they would have to be in the runtime assembly and you would use preprocessor arguments, #if UNITY_EDITOR to exclude the drawer and editor using
perfect, that worked @quartz folio :) thank you
how do i exclude the drawer, would that be #if not?
#else didn't seem to behave as expected
you wrap the drawer and using UnityEditor in the #if UNITY_EDITOR block
that way it only compiles if you're in the editor
I am having the same problem rn, did u find a solution?
jesus the amount of people who have this same issue is insane, its dumb af that unity havent added it as a built in feature
#archived-code-advanced for a possible solution. Just know how to calculate the right positions and use the right shader/layering to get the desired outcome
that's advanced?
No but the conversation was there
SteelCrow just mentioned another person in here having the same problem but the conversation was in advanced and too long to move it. rather fix it now and end the topic π
Yeah okay so LineRenderer works
Took me 2 minutes to google, find a thread mentioning it, and looking up the documentation. Just FYI, very often your question can be googled since there were many people before you with the same question.
Hey pls help i have set up multiplayer with this tutorial vvv But The Camrea you see from is not on the player i control pls help!
The second tutorial in my online multiplayer unity game series. In this we will look at how to create and join game lobbies/servers and how to add player movement.
Photon engine - https://www.photonengine.com/
Multiplayer episode 1 - https://youtu.be/nmPukdOsYQA
Player movement tutorial - https://youtu.be/YcJ8q8hEKm8
Animation tutorial - https:...
Take a deeeep breath, read #854851968446365696 how to ask questions and then come back with useful details about your issue
#854851968446365696 -> π€ Asking Questions
Please atleast provide your code and perhaps an example on what happends.
Alright later im busy now
π best answer
π€¦ββοΈ
Hello, I have been making a script to organise units in my RTS game but been having a little trouble telling them to rotate towards certain direction, e.g. here is the triangle script ```cs
var number_of_unit = Units.Length;
var triangle_base_size = Mathf.Round(Mathf.Sqrt(2*number_of_unit));
var unit_pos = mousePos - unitSpacing * new Vector2(0,triangle_base_size/2);
var unit_count_in_line = 0;
var unit_total_in_line = 1;
foreach(Unit x in Units)
{
x.AI.destination = unit_pos;
unit_pos.x += unitSpacing;
unit_count_in_line += 1;
if (unit_count_in_line >= unit_total_in_line)
{
unit_count_in_line = 0;
unit_total_in_line += 1;
unit_pos.y += unitSpacing;
unit_pos.x = mousePos.x - unitSpacing * (unit_total_in_line-1)/2;
}
}```
they always point downwards if anyone could give me some pointers on how to get them to look towards a different direction thatd be great, thanks
I am not really seeing a rotation going on here, can you explain a bit?
is just calculates the shape for the units to be in for a triangle formation but the triangle it organises these in always points down I was wondering if there is a fairly easy way to apply a direction for it to point to or if ill have to take a different approch
So the units point downwards or the triangle shape is pointing downwards? Either I am just too dumb to understand or its not clear what you actually wanna rotate.
the triangle shape points downwards
Ahhh, so you want to rotate your calculated triangle. Sounds like you need to create a position array/list to be able to iterate through those points and rotate them around the center of the triangle
yes, sorry im a bit clueless about how to do this, would I use something similar to rotate around? and how would I do that with a vector3 rather then transform?
I have researched this topic for roughly 2 hours. It is not as simple as you think and if you had actually read the messages clearly you would know that. Your attitude is pretty rude and belittling.
Read the messages in a whole different channel? Of course I didn't do that π
So I assume LineRenderer.SetPositions is not the solution?
(Also, giving tips is not a case of bad attitude)
They are in this channel, they are what I was replying too.
Nope its not.
Back to topic, did you see my solution in advanced? @amber haven Why is it not working for you
ill give it a look thanks
no I didn't see it, ill look over it now. thx for the help btw
What is the problem with it?
Rendering a line on the canvas, since line renderer works with 3d positions its very difficult to convert it to 2d while keeping it infront of the camera.
Again, did you check my solution in advanced, last time I ask π I am doing this exactly in that example...
Yeah I am now, sorry for the hold up I just had to deal with something irl
ill lyk when i have
LineRenderer.SetPositions works for that though, you just have to reference the relative point of the objects from the camera instead.
Twentacle indeed provided a solution for it
hi guys, does somewone know how to make a png work during runtime?? bc im importing an png image with www request and the background gets black instead of dissapear (idk if im in the correct channel so sorry) and thanks :)
!code please to make it readable for us
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class LoadTextureFromURL : MonoBehaviour
{
public string TextureURL = "";
// Start is called before the first frame update
void Start()
{
StartCoroutine(DownloadImage(TextureURL));
}
// Update is called once per frame
void Update()
{
}
IEnumerator DownloadImage(string MediaUrl)
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
Debug.Log(request.error);
else
this.gameObject.GetComponent<Renderer>().material.mainTexture = ((DownloadHandlerTexture)request.downloadHandler).texture;
}
}
Is your PNG having an alpha channel?
Hey, so uh this is a bit of a weird one but i'm basically trying to start a method from a different script and this error above shows up.
Upon further inspection, it turns out that it errors out in both of my methods for some reason but i have no idea why..
this is the code it was referencing in the console
and this is the methods that are having issues
im going to check
i dont think so
it uses a material
no, the image you load with your www request, that is an imagefile. you should check that this image file is actually transparent
and of course, your material needs to be transparent not opaque to actually use the alpha channel of your png
yes, the image is transparent
im going to see that
im trying with this image https://www.pngmart.com/files/4/Cube-PNG-HD.png
yep, it was the material π , thanks
How do you get the width of an image that is inside a canvas ?
Basically i want to make an XP bar like this . However, since the parent in white is set to Anchored, the width is always zero .. so i do not know how to set the width of the purple bar
You could just use the texture mode filled and use the value instead of setting the width of an image
what do you mean ?
.fillAmount and
You need to use a sprite
Ah !
I need to make a full white sprite t hen π
Neat ! thanks you
That simplifies all !
exactly, make one 16x16 white sprite that you can tint to whatever you need everywhere and just slice or fill it π
How would you code such "lines" pointing towards specific coordinates in 3D space?
Couldnt find any theory behind this, so any help appreciated
If you want them to point to a 3d object from a UI object, then you can use Camera.ScreenToWorldPoint to calculate the 3d point from the camera you invoke the method from, and draw a line from the UI object to the 3d object.
Alright, thanks a lot ! π
Could we even make them a bit curvy?
The method takes multiple points so you could split the lines up and create a curve.
Maybe add an option to specify the curve degree and amount of splits/iterations?
Alright thanks a lot ! ^^
Hi there, I'm trying to find some resources on how to take data from Google Sheets and load it into a game. I'm currently using a javascript script to export, then manually dropping the .json into the project, then using a C# script to organize the data but I'm wanting to streamline the process so when I add data, I don't have to update each script and manually download the .json. Does anyone know of any resources that could make this a more frictionless experience?
Can we make the TextMeshPro adjust its rect size in regards to the text size ( not the other way around ?)
you can use a parent layoutgroup / contentsize fitter to get a correct rect around it
any code in a code channel would be useful π
noones gonna read your code from a bad quality video π
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
And what exactly isnt working now?
Is the "Ontriggerenter called" firing?
Is it a trigger2d or trigger3d?
its 2D, so you should use the right method, OnTriggerEnter2D
How long is a sample from AudioClip.samples in milliseconds? The docs don't specify this or how that is calculated
question if anyone can give me a hint, i have a two 3d spheres in my game the blue and the red sphere, i wanna be able to press on blue sphere and move it along the red sphere edge using my mouse, any ideas how can i do that ?
blue_ position = (mouse_position-red_position).normalized() * red_radius
Hello, I have a sprite with a Sprite Mode set to Multiple. I load the asset into the game using Addressables and it is available as a Sprite class. Now, how do I iterate through all the sub sprites in the Sprite?
guys the fucking array doesnt show up
Is there anyway to store data in application memory rather than store in file memory, as we do with json
I want to store the data so that the users can't access it directly
Is there anyway to achieve that
so im trying to write an array of a class, that will allow me to create specific stuff for a cutscene, but the array isnt showing up
i cant figure it out
Add [System.Serializable] above Variables
ok thank you
???
you can encrypt it but people will sooner or later find a way to modify it
so don't rely on it
You can also try playerprefs, but that has a lot of issues, especially that it can only save float, int, and string
What should I use to save data locally then?
I was wondering if there was a way to store data in the application memory instead of file memory
Kindly tell me the appropriate method to save data
well the biggest issue with saving data is you need it to keep after the application closes. Unless you expect your users to never close the game or restart their computer....
@dusk apex I got it working. It turns out, caching the WaitForSecondsRealtime was the problem. I removed the variables and used new WaitForSecondsRealtime and it works now.
I am pretty sure I have heard before, that we can cache those and its a good thing to do instead of returning a new one everytime.
https://paste.myst.rs/q0m5wz4v Final Script.
a powerful website for storing and sharing text and code snippets. completely free and open source.
Are there any libs/assets to automatically connect two objects by a line or bezier curve?
I actually dont have any time to write one myself. That lib/asset should really just accept two objects and connect them via a line or curve...
Hey guys π
I'm trying to enforce the order of my fields in Json when stored in firebase. I'm using newtonsoft and "Jsonproperty" but it doesn't seem to work. Any ideas?
How can I get all the animated game objects from an animation clip in my script?
Never done it, but you could trying using "AnimationUtility.GetCurveBindings" apparently
Mmh.. but can I use it from outside the UnityEditor? (Because it seems to import UnityEditor)
hmmm good point. I don't think so :/
And also, how can I sample an animation clip from a script? Because the SampleAnimation function (https://docs.unity.cn/2017.4/Documentation/ScriptReference/AnimationClip.SampleAnimation.html) does not return anything.. what does it do?
will 15 lights per 80 unity units cause a lot of lag?
Like 80x80 plane, 15 lights in a grid
hello there, im having the issue that my player can jump very high after sliding down a wall and standing on the floor again
i can give code too
what brings the player to the ground? is it just gravity?
im using the unity physics but i have a script that causes the player to wallslide like that
what is in the player physics material
That depends on the sampling rate, but you can use AudioClip.length to get the seconds and calculate the milliseconds from that
its a rigidbody2d if thats what you mean?
0 friction, 0 bounciness
hmm
when you do the wallslide, does the superjump only happen right after, or what if you move around first? does it still happen?
the super jump only happens after tha player was on a wall, slid down and then touched the ground from where the player jumped without moving
wait i try to provide the script but my keyboard is tripping
ok its probably some weird velocity thing, im not sure
private bool IsWalled()
{
return Physics2D.OverlapCircle(wallCheck.position, 0.2f, wallLayer);
}
private void WallSlide()
{
if(IsWalled() && !isTouchingGround)
{
isWallSliding = true;
player.velocity = new Vector2(player.velocity.x, Mathf.Clamp(player.velocity.y, -wallSlidingSpeed, float.MaxValue));
}
else
{
isWallSliding = false;
}
}`` private bool IsWalled()
{
return Physics2D.OverlapCircle(wallCheck.position, 0.2f, wallLayer);
}
private void WallSlide()
{
if(IsWalled() && !isTouchingGround)
{
isWallSliding = true;
player.velocity = new Vector2(player.velocity.x, Mathf.Clamp(player.velocity.y, -wallSlidingSpeed, float.MaxValue));
}
else
{
isWallSliding = false;
}
}
not the cs in the beginning bruh
thats the wallslide
ok, check if isWallSliding stays true after the player comes off the wall
no i mean literally check in the inspector, public the variable
Sigh... Recently, when I start Unity, I get errors that the type or namespace "UI Document" can't be found, even though I've been using it extensively and haven't changed anything to it... Anyone know what might be wrong? Using 2020.3.40f1
Space in name?
this was very helpful because now i know that the problem is on my wallJumpCoyotetime thing
thanks!
i technichally have a timer for walljumping where it allows the player to jump a bit after being off the wall
Odd. When I change something in my code, save, go back to Unity, the errors go away. Even though I'm not changing anything to do with UI document.
I wanted to use graphics.blit to save a material to a texture, is that possible? By that I mean I have a complicated character customization shader where you can input multiple mask textures and set colour tints for individual elements. I want to bake the result of that to a single texture
Hey, so I have a shader which does some rendering and what not, but I would like to do something where I save the newly rendered frame somehow and then get the average of all the frames rendered from the beginning. A little like the code in this message. How would I go on about saving the render for a singular frame so I can use it later on?
_MainTex is already a variable in HLSL which gets updated when you render it, but I am not sure how I would save the old frame and use it
float4 frag (v2f i) : SV_Target
{
float4 oldRender = tex2D(_MainTexOld, i.uv);
float4 newRender = tex2D(_MainTex, i.uv);
float weight = 1.0 / (Frame + 1);
float4 accumulatedAverage = oldRender * (1 - weight) + newRender * weight;
return accumulatedAverage;
}
Hello, how can I face an object in direction of camera but rotation only on Z axis?
I tried with LookAt() but the result is wrong because modify all rotation my object rotate how I wish.
In first pic it's the desired result, the arrow need to be always in direction of the ground but when I start 2 pic it's what happen.
what is your goal?
To render my original shader, and then feed the texture and the last frames texture to the code I showed, so it can render an average of those 2 frames
i mean bigger picture
hdrp has a recipe for accumulation, and it is robust because it is used in their TSAA implementation
you can look at it. its source code is open
what is your shader trying to do?
like what is this for?
TSAA?
Anyway my point is going to be you should probably use shader graph and HDRP
Hi guys, anyone knows how a raycast can send me a hit with hit.point being origin of the level while I clearly wasn't there?
Using Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Ignore);
Where top/bottom/radius are the top/bottom/radius from my capsule collider, hitarray is an empty RaycastHitarray with 10 slots, dist is 0.01f
Reading the collider it tells me he hit the floor, so that's right too.
Yeah you right, I probably should. Thanks π
at least look at the hdrp source for how to do accumulation
the RTHandles class gives you accumulation buffers
this stuff is really hard. you can't just shove rendertextures onto a monobehavior
Function looks like
float radius = _playerCapsule.radius;
float height = _playerCapsule.height;
// Get top and bottom points of collider
Vector3 bottom = transform.position;
Vector3 top = transform.position + Vector3.up * _playerCapsule.height;
// Check what objects this collider will hit when cast with this configuration excluding itself
int hitLength = Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Ignore);
if(hitLength > 0)
{
// Sort array by distance from player, only sort part of array that contains the new hits
Array.Sort(hitArray,0, hitLength, _RaycastComparer);
hit = hitArray[0];
Debug.Log("HitLength: " + hitLength + " Hit object: " + hit.collider.name);
return true;
}
else
{
hit = default;
return false;
}
Getting debug logs with
HitLength: 1 Hit object: Floor
Grounded=True Angle=0 Ground normal=(0.00, 1.00, 0.00) Ground point=(0.00, 0.00, 0.00) Distance=0
While Ground point can't be true.
Most of the time it works fine but sometimes I get the wrong normal/point π
Also removed sorting, doesn't change behaviour though
Any ideas? Is there a bug within CapsuleCastNonAlloc?
it sounds like you're doing something pretty complex
what is your goal?
what is raycast comparer?
Using the same function for multiple casting purposes, this is ground check
Comparer<RaycastHit> _RaycastComparer = Comparer<RaycastHit>.Create((x,y) => x.distance.CompareTo(y.distance));
To sort the array by distance, so I get the closest hit
Did it without sorting, same issue so this can't be the problem
i mean i know what you said you want to do, but ordinarily it's pretty straightforward
it looks like you wrote C code in C#
Yeah, coming from C/C++ π
well
there's your problem lol
you're worrying about allocations instead of correctness
for something as straightforward and endlessly tutorialized as a ground check
who knows why it's giving a distance=0. it might not even be this code. if the rest of your project is as obscure as this snippet, you will have a lot of bugs
So what I wan't to achieve is casting my player capsule into a direction I want to see if there's a slope or wall ahead or if my player stands on something.
Writing my own kinematic character controller by the way
i have no insight*
because i have no idea what's going on
if you want to write C++ inside of unity, use DOTS
that is what it's meant for
then you can write 100% of the code, including the physics, and it can be as buggy as you want it to be
i'm exaggerating
but really, id on't think ther'es anything wrong with this code
I'm using CapsuleCastNonAlloc because it's way faster than the normal CapsuleCastAll most tutorials use
it doens't really make sense that it would be "way" faster
unless it just does something different
it might not query the latest state of physics or something
Doesn't need to allocate the memory all the time
listen
i'm only going to say this once
but your computer is allocating and deallocating memory literally a million times a second
so don't even start with that
that won't be the difference
this ground check is never going to show up in your profiler
but if "way faster" in dk999 speak means
100x faster
they're different functions
if the only difference is an allocation, it will not impact the profiler speed 99.9% of the time
where do i go for assistance with coding?
it will impact A column, but not THE column we are talking about
@opal cargo so they are probably different
i think if you are observing weird behavior, they are probably different
it's also possible it does not wipe the array correctly
try overwriting all the elements of the array with a new struct before you call it?
@opal cargo i would like to emphasize i really see nothing wrong with your code as you've written it
Tried overwriting but since CapsuleCastNonAlloc gives me how far it wrote into the array I should not need to
overwriting didn't fix the bug?
No
Depending on your experience, #π»βcode-beginner for beginner questions, this channel for general coding questions, #archived-code-advanced for advanced topics
and see if you get the bug
Good thing I come prepared, same bug with this code
Vector3 center = rot * _playerCapsule.center + pos;
float radius = _playerCapsule.radius;
float height = _playerCapsule.height;
// Get top and bottom points of collider
Vector3 bottom = center + rot * Vector3.down * (height / 2 - radius);
Vector3 top = center + rot * Vector3.up * (height / 2 - radius);
// Check what objects this collider will hit when cast with this configuration excluding itself
IEnumerable<RaycastHit> hits = Physics.CapsuleCastAll(
top, bottom, radius, dir, dist, ~0, QueryTriggerInteraction.Ignore)
.Where(hit => hit.collider.transform != transform);
bool didHit = hits.Count() > 0;
// Find the closest objects hit
float closestDist = didHit ? Enumerable.Min(hits.Select(hit => hit.distance)) : 0;
IEnumerable<RaycastHit> closestHit = hits.Where(hit => hit.distance == closestDist);
// Get the first hit object out of the things the player collides with
hit = closestHit.FirstOrDefault();
// Return if any objects were hit
return didHit;
okay well unequivocally there is nothing wrong here
i really don't think your snippet has any insights
i am sorry
Should I do this in Fixed Update or Update btw?
the trickiest part of the physics system is running the code at the right time
it's complicated, but it won't cause big issues
fixedupdate makes sense to me
as long as the "motor" for your character is run consistently before, or after, your "data gathering" stage, you are fine
if you interleave them, it might cause issues. but it would be odd to create incorrect hits
my suggestion is to filter out hits with invalid positions
if you are seemingly doing everything else correctly
is your character moving around a large concave mesh collider geometry?
No, just a flat cube.
My code isn't doing something way more complicated at the moment, just a little movement by grabbing input
void handleMovement(){
transform.eulerAngles = new Vector3(0,_orientation.eulerAngles.y, 0);
var viewYaw = Quaternion.Euler(0, _orientation.eulerAngles.y, 0);
Vector3 rotatedVector = viewYaw * _moveInput;
Vector3 normalizedInput = rotatedVector.normalized * Mathf.Min(rotatedVector.magnitude, 1.0f);
Vector3 movement = normalizedInput * _currentSpeed * Time.deltaTime;
if(_doJump)
{
_velocity += Mathf.Sqrt(_jumpHeight * -2 * (Physics.gravity.y * _gravityScale));
_doJump = false;
}
Vector3 moveDirection = transform.right * _currentSpeed * _moveInput.normalized.x + transform.up * _velocity + transform.forward * _currentSpeed * _moveInput.normalized.z ;
transform.Translate(moveDirection * Time.fixedDeltaTime, Space.World);
}
void handleGravity(){
if(_isGrounded && (_velocity < 0) )
{
_velocity = 0;
}
}
void FixedUpdate(){
checkGrounded(out RaycastHit groundhit);
handleGravity();
handleMovement();
}
Can't find any issue and this seems really basic
Orientation is just a cam-object that gets rotated via mouse, nothing fancy
yeah there's nothing here really
i'm not sure when the physics body gets updated when a transform is moved
void Moving()
{
Vector3 movement = p_input.xAxis * transform.right + p_input.zAxis * transform.forward;
movement *= speed;
movement += new Vector3(0, rb.velocity.y, 0);
rb.velocity = movement;
}```
hi sorry, im kinda lost. how do i rotate using this similar input? π¦ this is under player new input
What really bugs me is, the cast finds the floor as shown by the name of the collider, but the .point is just wrong
Is it maybe a overlap problem with the capsule?
Like contactOffset needs to be set or sth?
i'm sorry i just am not sure
i have never implemented my own kinematic character controller
if i were doing it today, and i had your background, i would use DOTS
because the physics engine is completely open source there
Maybe I consider that If I can't solve this.
But as you can see, nothing fancy there. Found an older Unity Forum entry where they discussed this and said it was an issue and fixed, maybe it's Back again
If I were to use LateUpdate it would override EVERYTHING in Update right? I've not used it often
Like say I set an agent's destination to somewhere in update
And then set it in LateUpdate
It would go to the destination in LateUpdate right?
Yeah it does
hey so im trying to rotate a player based on the angle of the ground under them in 2D, and right now im using two raycasts at the front and back of the player and then using the crossproduct of the points where the raycasts hit the ground to set the player rotation, but for some reason it isnt working.
`void Update()
{
//basic movement
if(Input.GetAxis("Horizontal") != 0)
{
body.AddForce(transform.right * speed * Input.GetAxis("Horizontal"), ForceMode2D.Force);
}
//raycasts for angle check
RaycastHit2D fHit = Physics2D.Raycast(fhitspot.position, -transform.up, groundmask);
RaycastHit2D bHit = Physics2D.Raycast(bhitspot.position, -transform.up, groundmask);
//rotates the player if grounded
if(isgrounded)
{
body.transform.rotation = Quaternion.Euler(Vector3.Cross(fHit.point,bHit.point));
}
}`
im still pretty bad at quaternions so im assuming its something to do with my crossproduct to quarternion thing
and what exactly is. "Isn't working"
like
it just doesnt turn
i checked if the raycasts were hitting the ground
and they are
checked how?
if(fHit.collider.tag != "ground") {Debug.Log("front didnt hit ground");}
i did that for both
I think the crossproduct is wrong
you want the angle between the two rays ?
and rottate player to that?
the angle between the points they hit
Hi guys. My Monobehaviour wasn't teal/working 'sometimes', but all the other stuff was. I reinstalled unity and visual studio 2019 and now almost nothing is 'functional' can you tell me what extensions I need to install to get the squiggly line parts to work properly?
hmmm maybe try
var forwardPoint = fHit.point;
var backwardPoint = bHit.point;
var direction = forwardPoint - backwardPoint;
var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
body.transform.rotation = Quaternion.Euler(0, 0, angle);```
what does underline say ?
that worked tysm
this is the monobehaviour one
weird. do you have any duplicate of this script
nope
try regenerate project files from Unity preferences settings
k 30 sec
awesome, everything seems to work after regen, ty
hmmm how do I do this correctly? trying to use generics with get set
{
get { return null; }
set {}
}```
this just gives me error CS1002: ; expected
A property can't be defined with generic type parameters, only types and methods.
I see...
How would I go about trying to make a list of components that I will later use for calling a function on the component. The list should be able to contain any type of function, but I will make sure to only add components that contain the correct function in them.
I tried this, but it didn't work because it says that Component does not contain a definition for 'Fire'.
public List<Component> components = new List<Component>();
components[0].Fire();
I will make sure to only add components that contain the correct function in them.
Then make a list of your component that has that Fire method instead, so you keep type safety
List<MyComponentWithThatMethod>
If there can be multiple component types with a Fire method, use an interface or a base class instead.
Yeah, there can be multiple components with the Fire method, but I'll do some research into base classes. Thank you.
Hmm, maybe there isn't a way to do this. I've used base classes before, I just didn't realize what they're called before; however, I don't think they'll work for this because I want each component to have a Fire method, but each components' Fire method should do a different thing i.e. turret will shoot 3 low damage fast bullets while cannon shoots 1 slow explosive bullet.
Abstract class, with an abstract Fire method. Inheriting classes will be forced to override the abstract method
Interfaces do the same thing, except you can implement multiple at once. Choose what suits you best
Oh, thank you!
hey I've made a finite state machine which uses classes derived from a base state class in order to handle different elements of my enemy code, i was wondering what the best sort of way to enable/disable some of the states at runtime would be? So basically have the ability to add and remove behavior deepening on the enemy type or creature (give example of base state and the logic in enemy class)
Do you want to accomplish this with just code or with a WYSIWYG editor (inspector or otherwise)?
Has anyone used the tilemap extras plugin to get the gameobject associated with a tile? Im struggling to figure out how to get a reference to the gameobject that was instantiated on a tile. https://docs.unity3d.com/Packages/com.unity.2d.tilemap.extras@4.0/manual/GridInformation.html
I am reading a midi file (which contains when each note in a song is played). I Start a coroutine for each note played that waits the seconds (with yield WaitForSeconds) until the note is in the song, which are like at least 1000 notes. Is it possible that that many co routines result in them not being accurate anymore? (they have a bigger and bigger delay for me)
Maybe there is a better way to accurately play the notes from a midi file?
You should avoid coroutines for basically exactly what you're experiencing. They're hard to line up, and even harder to keep track of. It will cause major performance issues especially if you're running multiples at once.
You can use a timer, tied to Time.DeltaTime, which will be more accurate to the computer itself.
You can bury timers inside of timers, use bools to handle which step its on. Set each timer to subtract and check if Timer <= 0 to run the next step. You're going to have a lot of nested timers and bools but itll bne more accurate.
As an alternative I believe there is a way to see where the audio player is in a given song, and set triggers based on that. I can't confirm that is a thing, as I've never done it, but I know with videos you can check which frame its on and run triggers based on that.
ty
me rewriting the same lines of code 5 times in a row hoping it will work this time:
it worked this time
use an asset store package
this is a complex problem
Well the funny part is that I just realized the notes were not delayed but too fast even (not sure if this is a coroutine bug or some other code bug)
Run the game with profiler on and you'll see how harmful coroutines are on performance, especially for something that is playing audio. You want to avoid them at all costs.
And I also found some other sort of solution to solve the problem. Just start the coroutines of notes being played within the next 5 seconds. Then call itself in 5 seconds. Then repeat. Then there will only be 10-20 active coroutines of the notes being played in the next 5 secs
would you say 10-20 is a lot?
More than 1 is a lot.
That's why I suggest using timers. Performance wise you don't want to sacrifice that much computation for audio.
Using a timer and time.deltatime will always target your computers performance and run smoothly. It's a little more coding but in the end saves you a lot of performance.
But I'm not playing the audio from the midi file, just showing the notes on screen. I have a different single audio file for the full song
Alright I'll take a look at that now
I think you could look into async, which is like a coroutine but runs simultaneously instead of bogging down the order of execution.
That is a lot more advanced though.
oh yea thats interesting
im using the mirror multiplayer system and i have it so it generates a code and hosts, but the code becomes the auto generated one, but i can move the code reverts to it's placeholder https://pastebin.com/tv9UV6Fa
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Does calling StopCoroutine after using a WaitForSeconds that hasn't finished yet in that coroutine mean that the code after the WaitForSeconds will still happen or not. I'm mainly asking because I have a Coroutine on an object, and when that object gets destroyed, I call StopAllCoroutines on it, but I'm getting an error from inside the Coroutine saying that I'm still trying to access it after it gets destroyed.
Once you destroy an object with a script all the script in that object goes to garbage collection
So you can't call a script once its been destroyed. Destroy will also wait till the end of the frame so you can add code after the Destroy and it will still run, but not after the object itself is gone gone
Hey guys
How do you prevent animations for resetting after a rapid keypress?
So, for example, you press D and it completes the animation sequence but when I rapidly tap D it resets it to the first frame of that animation
you need to block your "play animation" code from running while the animation is still in progress
can anyone explain what this code means
onFoot.Sprint.performed += ctx => motor.Sprint
More or less asking why you do "+= ctx =>" can anyone explain what it means
that is an anonymous function being subscribed to an event
equivalent to ```cs
onFoot.Sprint.performed += Handler;
void Handler(CallbackContext ctx) {
motor.Sprint();
}
So what exactly is ctx I should ask
info about the event being raised from the input action
which action it was, timing, phase, state etc.
I am kinda new to unity I know basic coding but not how the input system works
the input system can be a bit confusing
its basically 4 APIs/styles of doing input mixed into one package
So what does CallbackContext do
This is helpful too:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-subscribe-to-and-unsubscribe-from-events
Learn how to subscribe to and unsubscribe from events. Subscribe to events using the Visual Studio IDE, programmatically, or using an anonymous method.
Is it natural to not use some physics stuff in a 2d Platform game? For example, creating a gravity system instead of using Rigidbody 2D gravity variables
very common
most games don't use/want realistic physics for gameplay
Yup. I'm experimenting currently with messing with the physics to make jumping more satisfying, e.g. hang time at the peak of the jump, increased horizontal acceleration at the peak of the jump, cutting a jump short
Ic, thanks for the answers
Why is the attribute constructor not called?
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
public class GenerateEnum : Attribute
{
public GenerateEnum(string s)
{
Debug.Log(s);
}
}
``````cs
public class StringSplitter : MonoBehaviour
{
[GenerateEnum("TEST")]
public delegate void Hello();
}
Attributes are just metadata and cannot do anything by themselves. The constructor is called when the attribute is obtained through Reflection, through the GetCustomAttributes method.
ah, thank you.
Hi folks, so I'm new to unity but experienced with coding and C# so idk if i'm in the right channel, anyway I'm trying to understand the Unity project folder structure and where I should be placing my code. I use visual studio and my instinctive way to try and start a Unity project is to put the bulk of my game's code in a regular class library so that I can use it elsewhere, however it seems like Unity wants to be the 'root' of everything and not just a component in a larger project. Specifically the thing I'm trying to figure out is how to reference a .NET class library project (visual studio project) in a Unity project. So far all I've seen is that I need to take the DLL for the library and drop it into a 'plugins' folder, but that creates a need to have like a multi-step process every time I recompile my class library
think of a unity project as a .Net solution, you can make projects inside that solution with asmdefs (unity variant of .csproj), to add a .dll, you just need to put it somewhere inside /assets, if you have no asmdefs, all code will be compiled into a default project
alright so that's kind of what I'm afraid of, that Unity and Visual Studio are constantly 'fighting' over who gets to be the 'solution'
VS and Unity should not be fighting
when configured correctly
i don't mean literally but i mean like, conceptually
like having two friends who both think they should decide what the group is having for dinner
no
they do not do that when configured correctly
the unity VS plugin takes care of that
it generates all the required files to make VS believe everything is copacetic
if you edit the project files in VS, they get corrected immediately
yea, i'm using that plugin. I don't want to take up all your time - can you recommend a guide for setting up a proper folder structure and organization system in this type of case?
there isn't really a canonical way, but what works well for many people is making "module folders" along the lines of a traditional .net project Core/Shared/ModuleA/ModuleB/etc.
inside those its convenient to follow the recommeded unity package structure, i.e. 3 basic folders: Runtime/Editor/Assets
Runtime is for runtime only scripts, editor for stuff that depends on UnityEditor namespace and assets for anything serialized/art/models etc.
you'd keep any assets or plugins that do NOT have asmdefs in a folder named "Plugins" which causes them to becompiled to a separate DLL so they don't get recompiled every time you change some code in your app specific protion of the project
typically some assets also rely on specific folder structure, so you'd have to keep those at the root level
hm okay. tbh this seems like a mess but i guess most game engines are
its also a common practice to keep vendor assets (art mostly) in a separate root level folder
there is no way to avoid a mess in a project that does anything meaningful
best you can do is manage it
you could read the unreal engine best practice/styleguide on how to name and structure things, thats not entirely necessary in unity since you can easily search for types of files but its a great reference point do see how complicated this stuff can get
overall i'd say you can keep up the "put stuff into a library" workflow for the most part, its just way more involved because unity stuff involves so many different data/file types beyond just code and some xml/json and everything is making way more assumptions about what the purpose of the project is
this type of chaos seems akin to what modern ASP.NET MVC apps are like, especially when you start adding additional frameworks, there's just so much 'stuff' that it gets hard to manage even if it's organized well
yes exactly, its mostly this, different styles of doing things
there are so many ideas how to approach stuff in unity from really invasive, opinionated patterns like MVC in .NET to just some random person with zero architecture skills making a super useful library in their own style
mmmm describing MVC as 'really invasive, opinionated' is highly accurate lol
some really embrace "the unity way", some treat it like the worst idea ever
some like scriptable objects, some hate them
some like events, some don't. and most assets don't use other assets because of licensing restrictions, so everyone always reinvents the wheel
Hey I dont know if this question falls into this catigory but I have a helmet on my player(it is just a capsule) and the camera renders the helmet when you are in the game, I dont want this cause it obstructs most of the screen is there a way to fix this?
maybe show a picture of what you mean, typically: disable the renderer or change the model to render in the way you want
The sprite versus the first person view
i see why you want to change it but it kinda looks cool tbh
it does but it just totaly obscures the crosshair so when you ads you cant even see the iron sights
Just disable the mask when in first person mode?
how do I do that?
maskGameObject.SetActive(false) get a reference to your mask game object and call this when you are in first person mode
ok
You could also just disable the mesh renderer instead of the whole game object
ok
steamworks.net or facepunch?
heard the latter had some security stuff, not sure what it is, but also not sure if it's been fixed
Wait, facepunch offers network solution? I thought they have been using steamworks.net all this time? (I'm thinking of gmod?)
I think facepunch made the steamworks plugin for c#/unity
bu yeah same facepunch from gmod lol
They made one of the hundred wrappers that exist for steamworks
unlikely you're going to be making a multiplayer game with just that
ya wrapper there ya go
for (int i = 0; i < countLoaded; i++)
{
UnityEngine.Debug.Log(SceneUtility.GetScenePathByBuildIndex(i));
}```
Not sure why this is returning an invalid string
I have two scenes in the build settings, yet it's still returning blank.
shouldn't that be i instead of countLoaded
lol
it says "myRigidbody of birbscript is not assigned." Hlep me.
have you dragged a reference to the Rigidbody2D in the inspector?
oh, somehow i missed that part in the tutorial, ty
Why does this happen? Its all 0 when it's in vector form but not 0 when taken out individually..
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Because Vector3's ToString only uses 2 points of precision
That is not the question. My problem is whit the values being zero when in vector form and not zero when taken out individually.
I literally told you why
The values are the same in both, they're just printed to two points of precision when you use Vector3
Those are very small values close to zero so they get rounded when printing the vector
Oh.. now i understand.
1.22E-12 is 0.00000000000012 i think
But the values are zero in the inspector.
right, because it's showing you a rounded off number I think
So if we set the rotation of a game object zero. Its not actually zero? That doesn't make any sense.
It depends on where your 'zero' is coming from. "float rotation = 0.0f;" should be zero but if you're assigning the result of some computation and thinking it's zero, it may not be due to quirks with how computers handle floating point numbers
Smallest float is somewhere around 1E-38
These are the values in the inspector.
honestly @wary shadow you might want to read the MSDN article pages about the System.Single (aka 'float') type, there's a lot of information in there about how those types function
floats don't always roundtrip either. so like, float a = 1.0f; float b = a / 3.0f; float c = b * 3.0f; a == c // false, probably
(fixed, lol, it's late)
Where should I store then?
Oh my fault, single can represent 12e-12 by just setting the mantissa and exponent
This some Heisenberg shi*.π΅βπ«
So how do i consistently get the exact values in such cases?
Impossible ,compare two floating or double usually |a-b|<threshold
unity conveniently has Mathf.Approximately to compare floats
Or you just you two integers to represent a rational fractionβ¦.
But you should compute the simplified fraction each time
So in this case, how do i get value of x as zero ?
it basically is 0. as has already been pointed out, that number is incredibly small, it's just been displayed with only 2 decimal places
What's the actual problem though? Are you getting visual artifacts? Z-fighting?
Is there a way to combine meshes using AcquireReadOnlyMeshData and jobs?
Ok. Fortunately it only gives these wierd values when the rotation is zero. So i might be able to work around it.
what is the issue anyway?
I wanted to divide the value of x with another float. So theat was giving me wierd answers.
if you were dividing that number by another float it would still be so incredibly close to 0 that the difference would literally make no discernible difference because the number is already so incredibly close to 0 that it makes no practical difference
How should I store data in Android application to maintain privacy and prevent the user from altering the data?
there are very few sure-fire ways to completely prevent users from altering data stored on their devices. an easy way that would prevent someone casually attempting would be to just serialize to binary and save it as a file in Application.persistentDataPath
if you have data that 100% cannot be modified by users then it should be stored on a server that the game contacts to get and verify data. of course this would mean that the game has to have an internet connection to function
So like in only offline games
There's no better options than hashing or encrypting the data?
the best imo is always a server
pretty sure there are dedicated forums for that since nintendo is pretty strict about its NDAs
goodluck getting the nintendo unity version
probably the nintendo developer portal which you are surely already signed up on. of course i wouldn't actually know where since i'm not a nintendo dev π€·ββοΈ
thanks for the help tho
Does unity playerprefs and Android sharedpreferences do the same thing?
Is there any codesnippet to avoid the recttransform values to be stored as an override of prefabs? I have a dynamic content size fitter and it lerps the values, but using this in any kind of prefab just keeps adding the value as an override (makes sense, but we all know what fun it is to have prefabs in UI). So any suggestion is welcome here! π
How can I limit character typed in ui inputfield to 5?
inputfield.characterLimit
woops, you replied π
Hey Guys, pretty new to unity, starting my first software project (im a Embedded software developer for my normal job). Im currently working on a game, where i have a spawner that spawns objects at a specific frequency. I want those spawned objects to ignore each other in terms of collision but the following doesnt seem to work. Can anyone guide me in a different direction ?
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == gameObject.name)
{
Collider own_collider = gameObject.GetComponent<Collider>();
Collider other_collider = collision.gameObject.GetComponent<Collider>();
Physics.IgnoreCollision(own_collider, other_collider);
}
}
What ends up not working?
Like, what does the code do right now that is wrong?
the balls still collide
they dont pass trough each other
(sprite is a bit smaller than the collision box
Let's debug the code process first.
- Is
OnCollisionEnterexecuted at all? You can place aDebug.Logdown at the start of the method to verify. - Is
if (collision.gameObject.name == gameObject.name)passed? You can place aDebug.Log($"{collision.gameObject.name}, {gameObject.name}");down before the if-statement to verify the names of the gameobject and check if they are equal.
is the $"" similar to f"" in python ?
I think so
I notice the game is in 2d?
yes it is
You need this method, instead of what you have currently: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
doest the collision btw work if i dont have 'is trigger' enableD ?
Collision2D yes
hhmmm
Issue now is, it still collides the on the first frame
and then adds ignore collision and ignores its henceforth
I'm guessing Unity adds the exception on the next frame
yeah can imagine, better sollution would be to find all other balls in start and adds the ignore collision
Hello my physics2d.overlap circle is causing a distortion of 0.651848 x from the nearest wall ( i am trying to make a wall slide mechanic )
When i slide on the wall there is a 0.651848 x difference from the wall but when i remove that code it properly sticks to the wall
-2.02688 ( x value with wall slide on )
-1.375032 ( x value when wall sliding is done and when it sticks to the wall )
what am i doing wrong here
the overlap circle is supposed to be this much but it is more than that for some reason
also this value just changed so will the difference i assume
bit offtopic, but cool wizard!
thanks
I fixed it by keeping a list in my ballspawner and adding ignorecollision in the spawner
If you have a list, can't you just ignore the collisions as soon as the game starts?
I don't think they need to exist in the scene?
I see
so the list is gonna limited to 100ish balls
You could try visualizing your cast with the Gizmos class and OnDrawGizmos/OnDrawGizmosSelected function, or use a premade debugger, Ive found Vertx's very helpful: https://github.com/vertxxyz/Vertx.Debugging - depending how your handling your cast, maybe your players collider may be affecting the cast
okay thank you
also i am using a polygon collider should that make a difference ?
every place i checked they are using a box or a circle so i am just confirming
ok i can now confirm it is the overlapcircle
ok i have figured out my issue thank you so much
the gizmos helped!
i've encountered a weired question, when i use debug.log to output websocket message, it only print logs when i click on console message. How can I make it flush to console immediately.
Not sure what you mean with it only print logs when i click on console message.. What exactly are you clicking if it does not exist?
message like this
this is the log message when i change id code
and after this there should be chat info coming from websocket
however, those messages only print out when i click on these log blocks
i have a multiplayer game and everything is supposed to start in the menu scene
can i somehow make it so by pressing the play button the scene automatically gets changed to menu scene before the game even starts?
set the menu as the main scene
in the editor
in the editor iirc it starts with whatever scene you have open
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
What I've done in the past, I always include on each scene a prefab (i call it "SceneManager"), and inside the prefab's script it checks if currentScene == startingScene and if not, loads the starting scene. I think I also called it in OnValidate() so it would always execute before anything else, preventing a false start on any other objects' Awake() methods
nvm, i didn't do it OnValidate() ...
using UnityEngine;
public class Scenemanage : MonoBehaviour
{
void Awake()
{
GameObject check = //do the check
if (check == null)
{
Debug.LogWarning("No _app detected. Reverting to preload scene.");
UnityEngine.SceneManagement.SceneManager.LoadScene("preload");
}
}
}
A small-scale cooperative game sample built on the new, Unity networking framework to teach developers about creating a similar multiplayer game. - com.unity.multiplayer.samples.coop/SceneBootstrap...
Check out unity's boss room multiplayer sample, they have ton of very useful utilities and examples
you are at the start of a long journey
if you can avoid it, don't use scenes
finite state machine
Does unity player preferences and Android shared preference do the same thing?
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Idk but at an official Unity talk at GDC, they literally recommended to avoid PlayerPrefs and just roll your own
playerprefs are editable through regedit
making it unsafe
for android games, playerprefs are fine since few people will actually root their phones to have access to the files where the data is stored
How do i check if an object in an array has been deleted or is "Missing"?
Do i just do if(GO == null)?
Perhaps this?
check the index of the array
?
Yep a simple null check will do. Unity has overriden the == operator to also check for the destroyed state of the objects.
mhm, alright, let my try!
what about != so i can immediately negate it?
Same thing, when you override ==, compiler enforces that != is also overriden
Can json work with Android shared preferences?
idk, I was just adding a bit of my knowledge about playerprefs in the conversation lol

As long as that thing can take a string to store it somehow, then yeah JSON is supported
so this'll work?
Contains
?
Yes, for the null check. But no, since you're modifying the list you're iterating on with foreach
^
You should use a reverse for loop to pop elements from the end
use a for loop to modify list
whut? ._."
If you run this code you'll get an exception
Collection was modified, enumeration cannot continue
Or something
whut and question marks are kinda bad responses.. You should ask what exactly you're confused on..
What's the appropriate method to store data in offline games in Android then?
Binary
Files, dedicated app storage
I am being told that's not secure
Binary files aren't easy to read for regular joes
And it's slow to save in external memory
if the game is offline why do you care if it's modified
oh, my bad! I am confused what you mean by reverse loop,,,
like for (int i = list.Count - 1; i >= 0; i--)
I didn't say the shared preferences were excluded though. You can still use them whatever they are, as long as there's a way to interact with it that can take in strings (your JSON) and give them back.
If you need security, then encrypt the file. A determined user can still decompile your app to retrieve the encryption key, though. The most secure way to store data is to do so, on a server
ur right ._.
so then how would i do it?... without referencing it...? or what is going wrong?
You do it with the reverse for loop
you need a for loop whenever you want to modify a list while iterating
mhm, and what should that loop do?
wait, lemme think!
It throws the exception to avoid getting lost and giving random elements (or worse). It checks the "version" of the list each time it goes to the next element, and if it's different from the last "version", then the collection changed, throw!
By iterating over the list in reverse order, can remove elements from the list without affecting the index of the remaining elements
so this goes over the list in reverse?...
pretty much
iterate over the list in forward order, removing elements iirc cause the indices of the remaining elements to shift, which could cause errors or unexpected behavior
When you Remove an element, all the following elements shift right so they take the empty space
isn`t that good?
If you iterated forwards, then you would start skipping elements as the loop doesn't account for the shiftings
so this is how i should do it?
ooooh!... okay got it!
so it would always skip the 3rd entry, if 2 was null?
because 3 moves into 2's slot!
aaaah!
damn!
i didn`t think of it like that!

Thanks alot!
You'll notice now that your scoreboard text is backwards, probably, as the thing is now fully reversed
oh
Adding from the start of the text, instead of the end will fix it. And also you can use PlayerList.RemoveAt(i) since you now know what place to remove, instead of what object
https://hastebin.com/share/mapicizoje.csharp
Essentially what is going on is that I am moving the gameObject that the script is attached to back and forth between a undefined set loop of transforms using a horizontal input,
when going forward through the transforms, it will select the next one in line as the one to go to, however when going backwards for some reason, it doesn't select the one before it as the one it should be heading towards? (when it should)
any ideas of why this is happening? (Unity 2D URP)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how would i go about having parts getting glued together when someone in vr presses a button while holding it to another part and then when they press another it gets unglued?
parent them?
oh this sounds way easier than i thought
An easy way to have the gameObject's follow one another is to parent them, and if you were to move one gameObject next to the other gameObject before parenting them, it would give the impression they were glued together
if you're using rigidbodies you def need joints π
im gonna try putting one interactable in the other and see if i can still grab it how i want it to work
i think you should use an asset store asset to do this
there are really good ones
like VR Interaction Toolkit
i already am using that
this did not turn out well
maybe carefully read the docs
do you know how to program
start from the basics
public void Jump()
{
if (numberOfJumps < maxNumberOfJumps)
{
numberOfJumps++;
rb2D.velocity = new Vector2(rb2D.velocity.x, jumpForce);
}
}
private void FixedUpdate()
{
direction = playerInput.direction;
Vector2 move = new Vector2(direction * moveSpeed, 0f);
rb2D.AddForce(Vector2.ClampMagnitude(move, 16), ForceMode2D.Impulse);
}
i have this jump and move script but while im in the air my character moves way faster and clamping it doesnt stop that
You are clamping the amount of force you are adding, not the total force. It's most likely moving faster in air due to lack of friction.
Hello.
I'm trying to do this but with code
here is what I'm trying :
https://www.redblobgames.com/grids/hexagons/implementation.html#shape-triangle
I can't get this to work in C# though with tilemap.
Anyone know how I can get this working?
unordered_set<Hex> map;
for (int q = 0; q <= map_size; q++) {
for (int r = 0; r <= map_size - q; r++) {
map.insert(Hex(q, r, -q-r));
}
}```
wouldn't this be the exact same algorithm I helped you with before?
The only difference is you replace the neighbors() function with one that only returns the northest/northwest neighbors
Yes You did help me last time ty, but I have no clue how to modify this to do that π
this is the one from last time
https://hatebin.com/nzakuqzjdu
Pretty sure I just explained it π
The only difference is you replace the neighbors() function with one that only returns the northest/northwest neighbors
AH Ok I will try that
does the foreach need to change because I can't iterate through only 1/2 directions
Ok I think I got it ```cs
List<Vector3Int> Triangle(Vector3Int start, int maxDepth)
{
Dictionary<Vector3Int, int> depths = new();
Queue<Vector3Int> fringe = new();
depths[start] = 0;
fringe.Enqueue(start);
while (fringe.Count > 0)
{
Vector3Int current = fringe.Dequeue();
int currentDepth = depths[current];
if (currentDepth >= maxDepth) continue;
var neighborDepth = 0;
foreach (var neighbor in current.neighborsUp())
{
if (!depths.TryGetValue(neighbor, out neighborDepth))
{
depths[neighbor] = currentDepth + 1;
fringe.Enqueue(neighbor);
}
}
Debug.Log(neighborDepth);
}
return depths.Keys.ToList();
}```
@leaden ice is there a more modular way to this for the directions though, seems inefficient ?
public static Vector3Int[] neighborsUp(this Vector3Int vector)
{
return new Vector3Int[2]
{
vector.northeast(),
vector.northwest(),
};
}```
Hello I need help
I'm trying to code so enemies chase the player on a navmesh and stop when they are in front of the player's vision instead of moving to the side or behind the player
{
Vector3 viewDirection = player.transform.position;
viewDirection.y = transform.position.y;
transform.LookAt(viewDirection);
GetComponent<NavMeshAgent>().SetDestination(player.transform.position);
}```
this is what I have so far
you could have the search method take a delegate in for the neighbors function
so you can the search method
do you know what that would look like ? I'm a little confused on this part
I tried gpt it's saying I could pass the direction as parameter and then do this
Vector3Int[] directions = new Vector3Int[1] { Vector3IntExtensions.east(Vector3Int.zero) };
List<Vector3Int> Triangle(Vector3Int start, int maxDepth, Vector3Int[] directions)
{ etc.
foreach (var direction in directions)
{
Vector3Int neighbor = current + direction;
if (!depths.ContainsKey(neighbor))
{
depths[neighbor] = currentDepth + 1;
fringe.Enqueue(neighbor);
}
}```
doesn't work though πͺ¦
Help with navmeshagent early stopping
@leaden ice I got it working ! thanks again for the suggestion
List<Vector3Int> Search(Vector3Int start, int maxDepth, Func<Vector3Int, Vector3Int[]> neighborFunc)
Hello there!
I need help with a method
In the game there are row gameObjects which have tiles as children and I wrote a method to get the tiles of multiple rows at once which is called GetTilesOfRows() . Therefore I looped the GetTileOfRow() method. The problem with this was, that I wanted all the tiles that I got of every row to be returned in one array, the finalArray. Somehow a IndexOutOfRangeException occurs in the line allTiles[j] = tempAllTiles[j];.
{
GameObject[] allTiles = new GameObject[0];
GameObject[] tempAllTiles;
int allTilesAmount = 0;
for (int i = 0; i < rowNumbers.Length; i++)
{
int currentRowNumber = rowNumbers[i];
GameObject[] currentTiles = GetTilesOfRow(currentRowNumber);
int currentTilesAmount = currentTiles.Length;
// tempAllTiles has empty values until the currentTiles begin
allTilesAmount += currentTilesAmount;
tempAllTiles = new GameObject[allTilesAmount];
for (int j = 0; j < currentTilesAmount; j++)
{
// newTileIndex is the index of the allTilesArray until where the new tile will be
int newTileIndex = allTilesAmount - currentTilesAmount + j;
tempAllTiles[newTileIndex] = currentTiles[j];
}
// put the old tiles from previous rows from allTiles and the new ones from tempAllTiles together
int indexWhereCurrentTilesBegin = allTilesAmount - currentTilesAmount - 1;
for (int j = indexWhereCurrentTilesBegin; j < allTilesAmount; j++)
{
allTiles[j] = tempAllTiles[j];
}
}
return allTiles;
}```
GameObject[] allTiles = new GameObject[0];
your array explicitly has size 0
so obviously trying to put an object anywhere in this array will result in index out of range
You will need to either:
- initialize your array to the correct size (you need to be able to calculate what the final size of the array will be)
- use a List instead, which you can use Add on and it will automatically grow as required.
Okay, thank you very much! I think I will go by the list because in my opinion the code is to circuitously anyway
yes
Then you could, if you wanted to, really simplify your code want some help?
im not shure if later on the amount of children per row could vary
but still thank you
Got it, you can probably do this in a single line of code though =p
Look into IEnumerable.Select() and IEnumerable.SelectMany()
iΒ΄ll definitely do that, thanks
is there a way to do the following?
string method = "feedburger";
method();
private void feedburger()
{
return;
}
basically call my function using a string variable
just looked it up after figuring out how to word it. Is it Invoke?
update: I think it is
I have a master clock that tells me how many beats have elapsed, and I'm trying to add in the ability to drag in new audio clips so they start playing at the correct time. Here's my code for getting the correct beat time:
int playTime = (int)(main.beatsElapsed * 60f * audio.clip.frequency / baseTempo);
for some reason, this makes it play at the wrong time. Is there some sort of math error I'm making?
the base tempo is the bpm of the audio clip I'm putting in
oh my god it's because the beats elapsed started at 1 not 0
So I followed the Quickstart for configuring Visual Studio 2022. I'm using Unity 2021.3.22f.1. I installed the Unity dev workload, configured the editor to use VS2022, but intellicode still isn't working. I've tried restarting the hub and VS and Unity but nothing seems to work. Also, VS2022 doesn't show up in the Unity Hub Installs/Modules. Any other tips? Reboot my machine? Sacrifice a lesser goat?
yes, but if you are doing this, you are doing something wrong
it doesn't work that way
it will still be slightly off
yeah I realized afterwards
you should use an asset for sequencing audio or research it more
yeah I found a tutorial for it I'm using now
There's a specific package you gotta install with the vs code thing. It's like "desktop build tools" or something
what assets would you recommend?
not sure, i haven't used them so i can't give a real rec
you can also try the unity timeline which specially treats audio sequencing
you can use playablegraphs too
how do you move entities now that TransformAspect is gone? I'm just starting to learn aboutt entities and I can't find any tutorials that don't use TransformAspect.
how would i go about making a quake style camera tilt when strafing? ive looked everywhere online cant find any working code and when i try to do it my self theres lots of problems
rotate the camera's transform.rotation while moving
yeah thats what im trying to do
but it doesnt work when i rotate on the y axis
move the GameObject's transform.position
post your code
i got this code to work but when i move from left to right it doesnt smooth it
Quaternion finalRot = Quaternion.Euler(xRotation, yRotation, rotZ);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, finalRot, _rotationSpeed);
}```
when you say "smooth", you mean it's just going from level to tilted immediately?
and you want it to reach the final tilt gradually?
lemme record a vid
wouldn't that defeat the point of using entities?
what do you mean specifically by "entities"? entity is a very vague word that doesn't really have any meaning, so i'm assuming by entity you mean :
- a GameObject, which
- has been Instantiate<>() 'ed
it looks smooth to me... you mean when going from left to right, it's a very sudden jerking motion?
when i go right and let go its ok but when i switch immediately it doesnt smooth
no at 0:07 i start going left to right fast it isnt smooth
Sorry, I should have used the dots forum. I'm talking about the entities package
can i see a larger code snippet? what you posted looks correct
this is my entire cam script ``` public class PlayerCam : MonoBehaviour
{
public float sensativityX, sensativityY;
public Transform player;
public Transform cameraPosition;
public Transform orientation;
float xRotation;
float yRotation;
public float _tiltAmount = 5;
public float _rotationSpeed = 0.5f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
Tilt();
transform.position = cameraPosition.position;
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensativityX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensativityY;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
yRotation += mouseX;
Vector3 v = transform.rotation.eulerAngles;
transform.localRotation = Quaternion.Euler(xRotation, yRotation, v.z);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
public void Tilt()
{
float rotZ = -Input.GetAxis("Horizontal") * _tiltAmount;
Quaternion finalRot = Quaternion.Euler(xRotation, yRotation, rotZ);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, finalRot, _rotationSpeed);
}
}```
do me a favor and edit that to include "cs" immediately following the 3 beginning tilde's (`)
just to add some color for me
@vapid patrol ^
i still don't see the colors but that's okay -- it looks like at the end of your Update() function you're setting the rotation, then also setting it at the begining through Tilt()
Pretty sure that's causing the issue, based on what I can see
public class PlayerCam : MonoBehaviour
{
public float sensativityX, sensativityY;
public Transform player;
public Transform cameraPosition;
public Transform orientation;
float xRotation;
float yRotation;
public float _tiltAmount = 5;
public float _rotationSpeed = 0.5f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
Tilt();
transform.position = cameraPosition.position;
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensativityX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensativityY;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
yRotation += mouseX;
Vector3 v = transform.rotation.eulerAngles;
transform.localRotation = Quaternion.Euler(xRotation, yRotation, v.z);
orientation.rotation = Quaternion.Euler(0, yRotation, 0);
}
public void Tilt()
{
float rotZ = -Input.GetAxis("Horizontal") * _tiltAmount;
Quaternion finalRot = Quaternion.Euler(xRotation, yRotation, rotZ);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, finalRot, _rotationSpeed);
}
}```
colors?
thats better lol. colors
yay
ill try removing it
wait should i just remove the orientation.rotation = Quaternion.Euler(0, yRotation, 0); or what
im dumb
@red scarab
@red scarab yo i just fixed it by going to inputs and disabling the snapping on the axis
it worked
thanks
u the π
i made another axis for the script called HorizontalCam so i can still use snapping on my movement axis π
changing the speed variable does nothing tho idk why its not too bad tho
oh wait it does work but only if i set the tilt to something crazy like 90
ok i should go sleep lol
Hi guys let's see if you can help me out here
I'm making a state machine to control all my enemy characters. The state machine itself looks like this
public class StateMachine<T> where T: Entity
{
public State<T> CurrentState { get; private set; }
public void Initialize(State<T> startingState)
{
CurrentState = startingState;
CurrentState.Enter();
}
public void ChangeState(State<T> newState)
{
CurrentState.Exit();
CurrentState = newState;
CurrentState.Enter();
}
}
As you might see, the CurrentState variable is generic since the state itself should be able to access the entity it is controlling.
public abstract class State<T> where T: Entity
{
// To be able to change the state of the entity
protected StateMachine<T> stateMachine;
// To be able to access the gameobject itself
protected T entity;
public State(T entity, StateMachine<T> stateMachine)
{
this.entity = entity;
this.stateMachine = stateMachine;
}
Both this classes' generics should inherit from Entity which is the script that is actually attached to the gameobject.
public abstract class Entity : MonoBehaviour
{
// Let every entity have its own state machine with its own states
public StateMachine</*What to put here?*/> stateMachine;
// More code...
}
There issue here is that every Entity requires a state machine to handle its states but StateMachine is generic over Entity so I have circular generics.
I tried passing this as the generic type of StateMachine but it requires a type known at compile-time. What's the best way to keep it as abstract as possible without having this issue?
what is your big picture goal?
A generic state machine that works for every enemy entity (maybe even the player itself)
Hey guys I was trying to make something save in a scene in Unity
I have a boolean in a scene that is false
In the scene after playing some of the game, the boolean turns to true
When I leave that scene and come back the boolean is reset to false, can anyone please explain how I can make the boolean save if its true or false and it wont reset if I exit the scene?
You can't, as you generally don't modify the scene files at runtime. You can save your changes to a different file and apply them whenever you load the scene
Would you be willing to help me make this please
So basically I would be able to save the boolean into a seperate file, and when I load the scene the boolean would be applied right?
You have to write the code to make that happen
im 100% lost on how to do the saving into the file and loading it into the seen, I have never done anything like this before and this is my first game
Look up saving and loading systems and you should find bunch of material
ok thanks, but 1 question I would be able to save it to the file during the game is running right? the game wont have to stop to save it and load it correct?
When your game is stopped your code won't be running so that would make little sense
Small amount of data saves and loads very quickly
I was tring to use unit tests in playmode, but I need it to work after the other scripts in the scene run the awake method, is it possible?
You could just do a yield return null to wait one frame in a coroutine test for example
maybe change script load order priority from the project settings? idk
Hi guys let s see if you can help me out
Hah. I had to right click the incompatible assembly in the solution and reload it manually.
I have an object performing a somewhat costly check in it's update thread, but I don't actually need the script to update often (but do need it to run in the background)
basically, it's sequencing relative to other events is entirely unimportant. Is there an "async" equivalent to update I could run here, or something similar?
Coroutine
wouldn't that update just as often as the main thread? or do I use waitforseconds and have the coroutine restart itself?
yeah you can use a waitforseconds to delay it and let it repeat every so many seconds
Pretty sure coroutines don't operate on a different thread
I've never used them, so someone else will have to verify.
they 100% do not operate on a different thread
but I think he's right in that his solution is more performant (although still on the main thread)
You can write your own batch thing
one tick, check first 1/3 of items
next tick 2/3
next tick, 3/3
The problem with using threads, is that if you're not careful, you'll spend more time actually getting the data between threads, than your current bottleneck
and then you have thread safety, etc
yeah I'm aware of the risks of splitting info across threads, I was hoping due to the asynchronous nature of this specific case that it wouldn't be a problem
Ensure that you're not running everything in update()
ofc
Your simulation code should run in fixedupdate
along with pretty much everything important
simply use update() to interpolate and render
You also need to manage your garbage collection activity, if you're looking for performance
allocating a ton of crap every time your game updates is going to make things run slow
You should probably post the object's "costly check" here so that other people can take a look at it.
I actually fixed that specific case, it was a simple logic error, but I'm more interested in the general discussion bc I do commonly have situations where I need something to be continually updating in the background but the rate at which it updates isn't important
Yeah running everything in update is a huge waste
and a lot of people do it because they're unaware of what they're doing
if (transform.InverseTransformPoint(playerTransform.position).z > 0)
{
if (!hasPlayerEntered)
{
hasPlayerEntered = true;
PartySceneSingleton.Instance.isPlayerInRoom = true;
}
}
else
{
if (hasPlayerEntered)
{
hasPlayerEntered = false;
PartySceneSingleton.Instance.isPlayerInRoom = false;
}
}
this was the code causing issues, I was updating the value in the singleton more than once per change, when my intention was to only do it once per change. Fixing that solved the problem
I'm not 100% sure update vs fixed update is going to matter a ton on low end hardware. Won't fixed update execute multiple times on a frame if the framerate is low?
Unity's FixedUpdate only runs on render frames. There's really nothing special about it. It does, however, only run on certain render frames at a specific interval
I understand it's essential for anything involving rigidbodies but I mean I'm not sure about update vs fixedupdate as a one size fits all thing
nevermind TIL
Unity's update loop is all single threaded. It all happens sequentially
while (timer >= Time.fixedDeltaTime)
{
timer -= Time.fixedDeltaTime;
Physics.Simulate(Time.fixedDeltaTime);
FixedUpdate();
}```
Imagine this inside of an update loop. This is how unity's fixedupdate works
To get our interpolation alpha, all you need to do is timer / time.fixedDeltaTime. This will return a value from 0 to 1 that specifies how far we are in the current tick.
We're delving into advanced territory, but you get the point.
I need help with changing to a layer on a gameobject that effects the children
U want to change layer and have all children change with it?
Does this need to happen at runtime?
yes and yes
I have a script to change one gameobjec but I dont want to apply it to all the gameobjects
Wait u do or u dont wanna apply to all children too?
Oh u mean the script
Yeah understandable
Well u could get all children of the gameobject by doing foreach (Transform child in transform) { }
This only goes 1 child deep though
So children of children arent found
damn
this is what I have rn
if (other.gameObject.CompareTag("Light"))
{
gameObject.layer = 3;
}
Best way to get all of em is this i think:
private void ChangeChildLayers(Transform trans)
{
foreach (Transform child in trans)
{
child.gameObject.layer = 3;
ChangeChildLayers(child);
}
}
Hope this helps
Is there anyway to get around the vector3 doesnβt accept doubles thing?
Edited
oh lol
(float)myDouble
Doesnβt that convert to float?
does it need to be doubles?
Vector3 only accepts float
And int i think
yea most likely would never need a double really, unless idk Kerbal Space Program. π€·
I believe so. Itβs a ballistic simulation that works with small numbers and I think the lack of precision is causing it to act weird
Unity's simulation only uses floats
the second your numbers get plugged back into unity, they're floats
That seems useful thank you
can you perform the double operations on your own and then cast it to a float at the end?
Potentially. That may be a good enough solution now that I think about it. Donβt know how that slipped my mind. Thanks.
yeah should reduce most of the imprecision 
You haven't passed a parameter in.
I dumb
π
Even nicer would be if u would replace β3β with newLayer int as parameter that can be different whenever ChangeChildLayer is called
Then u can also make it set to other layers if u want. Maybe when u wanna change to another layer
maybe
i would remove the if statement in the ChangeChildLayers method, may or may not cause it to not work depending on how you set up your game.
Nice
Hey guys so I was using PlayerPrefs and basically I have the same script attached to 5 different levels of my game
And since the PlayerPrefs are not specific to one scene, they get carried over to the next level and ruin the next level
Is there a way I can make PlayerPrefs unique for each different scene so that they dont ruin each different level but still work for the level they are supposed to work for?
use the scene index as part of the player pref key
Wait this confused me, I can show you what I have
highscore = PlayerPrefs.GetInt("highscore" + SceneManager.GetActiveScene().buildIndex, 0) would retrieve the value from key "highscore1" if you are on scene 1 for example
wait your so smart tysm
What do I use to store information about a sprite
Assets\Control.cs(20,16): error CS0029: Cannot implicitly convert type 'UnityEngine.Collider2D' to 'string'
{
public float movespeed = 10;
bool follow = false;
string owo = "collider";
// Start is called before the first frame update
void Start()
{
}
private void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log("woow");
Debug.Log(Random.Range(0,10));
owo = collider;
Debug.Log(owo);
follow = true;
}
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * movespeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * movespeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector2.down * movespeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector2.up * movespeed * Time.deltaTime);
}
if (follow == true)
{
owo.GetComponent<Collider>().GetComponent<Transform>().position = gameObject.GetComponent<Transform>().position;
}
}
Im trying to get the information from OnTriggerEvent to store into the variable that is named owo. It wont store right.
Okay, at this point I have no idea what to do. I've tried using Find() and transform.GetChild().
I have this hierarchy.
And these definitions:
[SerializeField] private Transform ui;
[SerializeField] private GameObject title_screen_ui;
[SerializeField] private GameObject lives_ui;
[SerializeField] private GameObject turn_menu_ui;
[SerializeField] private GameObject turns_ui;
[SerializeField] private GameObject opponents_turn;
[SerializeField] private GameObject your_turn;
[SerializeField] private GameObject press_to_start_button;
[SerializeField] private Button start_game_button;
[SerializeField] private Button attack_button; ```
Instead of using [SerializeField] private I would like to instead have my inspector show less fields and to make the references to the children in the code directly
Assigning in the inspector is the preferred method.
But transform.Find and transform.GetChild etc should work fine, generally
what exactly are you trying to store? the name of the collider?
I've been told that assigning in the inspector takes up more performance in total though, and I'm supposed to get as much performance out of it as possible
I havent even seen what sort of command takes more or less performance to get the same task done. I was just thinking that the fewer steps there are, the less performance it would require. So it never made much sense to me that doing anything other than assigning in the inspector would take up less performance.
So my question is, is there anything that could make this more performance efficient? Or to have better code practice?
Yes
No idea where you heard that thing about performance. It's false
I want the name of the object being hit so that I can use it to change its position
so do you want the transform of the collider then?
it doesnβt sound like you need to store the name, just the transform
Idk, I need to get the transform to happen continuously
Why do you need the name to change its position?
Because the object of which Iβm changing is not the one containing the script
You just need a reference to the Transform
So?
Learn to work with references in C#