#archived-code-general

1 messages Β· Page 71 of 1

dusk apex
#

Everything is up in the air, if so.

mint moat
#

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.

dusk apex
#
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

mint moat
#
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```
dusk apex
#
Round Started
  Bullet Fired 1
Wait for x seconds
  Bullet Fired 2
  Bullet Fired 3
  Bullet Fired 4
mint moat
#

Thats the issue from the starting, It shouldn't fire next round immediately

dusk apex
#

It shouldn't.

mint moat
#

but here it does

dusk apex
#

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.

mint moat
#

Ok so let me record the insepector and share the script used .

dusk apex
grave crane
#

does onDrawGizmos work in a StateMachineBehaviour?

dusk apex
#

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++;
        }
}```
mint moat
static matrix
#

I am

#

The try catch also isnt working

dusk apex
static matrix
#

Which shouldnt

dusk apex
#

I'm assuming some custom type?

mint moat
dusk apex
#

If it's a List it would be accurate

static matrix
#

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

leaden ice
#

Show the actual full error message

dusk apex
#

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.

static matrix
#

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

leaden ice
#

Also Instead of try/catch you should just be checking the Count

static matrix
#

I am

leaden ice
static matrix
#

ayy Praetor You god resident good for you

dusk apex
#

Show your logs of it's size being two.

static matrix
#

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

mint moat
#

I hope you are getting whats teh problem here

sinful terrace
#

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

mint moat
#

You can convert local axis to global using TransformDirection and then apply the velocity normally...

cunning trout
#

hi!
Is there a way to reference a Light2D in a script?

mint moat
#

using UnityEngine.Experimental.Rendering.LWRP available here

quartz folio
#

LWRP hasn't been a thing for years.

#

Or just get your IDE to tell you

hexed pecan
#

Or yeah what volkner said

sinful terrace
#

i made some very dumb code before i knew that

#

that only broke thins more

restive igloo
#

Just wondering are job posts allowed here?

quartz folio
tawny elkBOT
restive igloo
mystic ferry
#

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

cosmic rain
#

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.πŸ€”

mystic ferry
#

that would work but there's a LOT of physics I'd have to handle doing it that way

cosmic rain
#

Also, you could stop the paddles from passing through the walls manually too.

mystic ferry
#

I'd like to leave as much as possible up to the physics engine if I can

cosmic rain
#

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.

mystic ferry
#

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

cosmic rain
#

It's simply applying forces based on the paddle velocity, mass and collision normal I think.

mystic ferry
#

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

cosmic rain
#

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.

mystic ferry
#

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?

quartz folio
mystic ferry
#

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

mystic ferry
quartz folio
#

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

worldly hull
#

i need to use async inside a coroutine , and i found out something like IAsyncEnumerator

#

but i dont want to return a type

cosmic rain
cosmic rain
worldly hull
#

this is from a coroutine, the function awaiting is retrieving a string of jsondata

in this case, is await same as yield return?

spring basin
#

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?

cosmic rain
tidal rampart
#

What is the use of void?._.

cosmic rain
inland arrow
#

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

shell scarab
inland arrow
#

Alright, i'll try that.

#

alright, i've changed the name, but im getting a similar error regardless

quartz folio
#

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

inland arrow
#

oh, so they can't be in the same script file together?

shell scarab
#

they can be

#

just surround the attribute with that conditional compilation (idk what called)

#
#if UNITY_EDITOR
// stuff
#endif
#

works for me

quartz folio
#

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

inland arrow
#

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

quartz folio
#

you wrap the drawer and using UnityEditor in the #if UNITY_EDITOR block

#

that way it only compiles if you're in the editor

inland arrow
#

oh, right

#

i had them backwards, sorry

amber haven
#

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

plucky inlet
#

#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

swift falcon
#

that's advanced?

plucky inlet
#

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 πŸ˜„

thin aurora
#

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.

topaz gate
#

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!

plucky inlet
thin aurora
topaz gate
#

Alright later im busy now

plucky inlet
#

πŸ˜„ best answer

thin aurora
#

πŸ€¦β€β™‚οΈ

subtle raptor
#

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

plucky inlet
subtle raptor
plucky inlet
#

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.

subtle raptor
plucky inlet
#

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

subtle raptor
amber haven
thin aurora
#

So I assume LineRenderer.SetPositions is not the solution?

#

(Also, giving tips is not a case of bad attitude)

amber haven
plucky inlet
#

Back to topic, did you see my solution in advanced? @amber haven Why is it not working for you

subtle raptor
amber haven
thin aurora
amber haven
#

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.

plucky inlet
amber haven
#

ill lyk when i have

thin aurora
#

Twentacle indeed provided a solution for it

languid saddle
#

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 :)

plucky inlet
tawny elkBOT
#
Posting 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.

languid saddle
# languid saddle hi guys, does somewone know how to make a png work during runtime?? bc im import...
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;
    }
}
plucky inlet
rose silo
#

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

languid saddle
#

i dont think so

#

it uses a material

plucky inlet
#

and of course, your material needs to be transparent not opaque to actually use the alpha channel of your png

languid saddle
#

yes, the image is transparent

languid saddle
#

yep, it was the material πŸ˜… , thanks

wary wagon
#

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

plucky inlet
wary wagon
#

what do you mean ?

plucky inlet
#

.fillAmount and

wary wagon
#

I do not have these options

plucky inlet
#

You need to use a sprite

wary wagon
#

Ah !

#

I need to make a full white sprite t hen πŸ˜„

#

Neat ! thanks you

#

That simplifies all !

plucky inlet
ember ore
#

How would you code such "lines" pointing towards specific coordinates in 3D space?
Couldnt find any theory behind this, so any help appreciated

thin aurora
#

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.

ember ore
thin aurora
#

Maybe add an option to specify the curve degree and amount of splits/iterations?

ember ore
#

Alright thanks a lot ! ^^

vivid basalt
#

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?

wary wagon
#

Can we make the TextMeshPro adjust its rect size in regards to the text size ( not the other way around ?)

plucky inlet
#

any code in a code channel would be useful πŸ˜‰

#

noones gonna read your code from a bad quality video πŸ˜„

#

!code

tawny elkBOT
#
Posting 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.

plucky inlet
#

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

steep prism
#

How long is a sample from AudioClip.samples in milliseconds? The docs don't specify this or how that is calculated

onyx mango
#

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 ?

uncut plank
spring basin
#

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?

mossy gust
#

guys the fucking array doesnt show up

plush sparrow
#

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

mossy gust
#

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

quartz folio
#

Add [System.Serializable] above Variables

mossy gust
#

ok thank you

uncut plank
#

so don't rely on it

static matrix
plush sparrow
#

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

static matrix
#

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....

mint moat
#

@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.

ember ore
#

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...

fading yew
#

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?

deep fable
#

How can I get all the animated game objects from an animation clip in my script?

fading yew
deep fable
fading yew
#

hmmm good point. I don't think so :/

deep fable
static matrix
#

will 15 lights per 80 unity units cause a lot of lag?
Like 80x80 plane, 15 lights in a grid

old laurel
#

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

static matrix
#

what brings the player to the ground? is it just gravity?

old laurel
#

im using the unity physics but i have a script that causes the player to wallslide like that

static matrix
#

what is in the player physics material

hexed pecan
old laurel
static matrix
#

this thing

#

what are its stats

old laurel
#

0 friction, 0 bounciness

static matrix
#

hmm

#

when you do the wallslide, does the superjump only happen right after, or what if you move around first? does it still happen?

old laurel
#

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

static matrix
#

ok its probably some weird velocity thing, im not sure

old laurel
#
 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

static matrix
#

ok, check if isWallSliding stays true after the player comes off the wall

old laurel
#

like this?

        else if(isTouchingGround)
        {
            isWallSliding = false;
        }
#

nvm not like this

static matrix
#

no i mean literally check in the inspector, public the variable

golden dove
#

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

static matrix
#

Space in name?

old laurel
static matrix
#

thanks!

old laurel
#

i technichally have a timer for walljumping where it allows the player to jump a bit after being off the wall

golden dove
signal bane
#

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

viral pilot
#

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;
}
cursive shoal
#

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.

viral pilot
# polar marten 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

polar marten
#

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?

polar marten
opal cargo
#

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.

viral pilot
polar marten
#

the RTHandles class gives you accumulation buffers

#

this stuff is really hard. you can't just shove rendertextures onto a monobehavior

opal cargo
#

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?

polar marten
#

what is your goal?

#

what is raycast comparer?

opal cargo
#

Using the same function for multiple casting purposes, this is ground check

opal cargo
#

To sort the array by distance, so I get the closest hit

polar marten
#

i think that is probably the issue

#

but i can't tell what this is doing

opal cargo
polar marten
#

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#

opal cargo
polar marten
#

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

opal cargo
#

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

polar marten
#

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

opal cargo
#

I'm using CapsuleCastNonAlloc because it's way faster than the normal CapsuleCastAll most tutorials use

polar marten
#

unless it just does something different

#

it might not query the latest state of physics or something

opal cargo
#

Doesn't need to allocate the memory all the time

polar marten
#

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

pastel remnant
#

where do i go for assistance with coding?

polar marten
#

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

opal cargo
polar marten
opal cargo
#

No

polar marten
#

okay well

#

try it with CapsulCast

#

without nonalloc

thin aurora
polar marten
#

and see if you get the bug

opal cargo
# polar marten 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;
polar marten
#

i really don't think your snippet has any insights

#

i am sorry

opal cargo
#

Should I do this in Fixed Update or Update btw?

polar marten
#

the trickiest part of the physics system is running the code at the right time

opal cargo
#

Maybe that's the problem

#

Doing groundcheck in FixedUpdate though

polar marten
#

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?

opal cargo
#

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

polar marten
#

i'm not sure when the physics body gets updated when a transform is moved

wide fiber
#
 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
opal cargo
#

Is it maybe a overlap problem with the capsule?

#

Like contactOffset needs to be set or sth?

polar marten
#

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

opal cargo
languid hound
#

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

lucid scarab
#

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

potent sleet
lucid scarab
#

like

#

it just doesnt turn

#

i checked if the raycasts were hitting the ground

#

and they are

potent sleet
#

checked how?

lucid scarab
#

if(fHit.collider.tag != "ground") {Debug.Log("front didnt hit ground");}

#

i did that for both

potent sleet
#

I think the crossproduct is wrong

potent sleet
#

and rottate player to that?

lucid scarab
#

the angle between the points they hit

north gazelle
#

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?

potent sleet
# lucid scarab the angle between the points they hit

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);```
north gazelle
potent sleet
north gazelle
#

nope

potent sleet
north gazelle
#

k 30 sec

north gazelle
hoary steeple
#

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

static matrix
#

Big brain

#

sarcasm

#

not very big brain

#

but it works

late lion
hoary steeple
#

I see...

inner yarrow
#

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();

simple egret
#

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.

inner yarrow
#

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.

simple egret
#

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

frosty creek
#

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)

proven plume
cloud smelt
feral mica
#

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?

cobalt flint
feral mica
#

I thought so, but thanks for confirming

#

any idea how I should do this?

cobalt flint
#

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.

feral mica
#

ty

static matrix
#

me rewriting the same lines of code 5 times in a row hoping it will work this time:

#

it worked this time

polar marten
#

this is a complex problem

feral mica
#

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)

cobalt flint
#

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.

feral mica
#

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?

cobalt flint
#

More than 1 is a lot.

feral mica
#

πŸ˜„

#

rip

cobalt flint
#

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.

feral mica
#

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

cobalt flint
#

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.

feral mica
#

oh yea thats interesting

onyx saddle
inner yarrow
#

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.

cobalt flint
#

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

vagrant harbor
#

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

cold parrot
random sandal
#

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

cold parrot
#

equivalent to ```cs
onFoot.Sprint.performed += Handler;
void Handler(CallbackContext ctx) {
motor.Sprint();
}

random sandal
#

So what exactly is ctx I should ask

cold parrot
#

info about the event being raised from the input action

#

which action it was, timing, phase, state etc.

random sandal
#

I am kinda new to unity I know basic coding but not how the input system works

cold parrot
#

the input system can be a bit confusing

#

its basically 4 APIs/styles of doing input mixed into one package

random sandal
#

So what does CallbackContext do

cold parrot
#

provides context information

#

its an event argument

shell scarab
random sandal
#

Thanks you two πŸ™‚

#

Oh wow there is a server for input system in general..

noble surge
#

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

cold parrot
#

most games don't use/want realistic physics for gameplay

strong cloud
#

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

noble surge
#

Ic, thanks for the answers

shell scarab
#

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();
}
late lion
unreal zinc
#

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

cold parrot
unreal zinc
#

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'

cold parrot
#

when configured correctly

unreal zinc
#

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

cold parrot
#

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

unreal zinc
#

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?

cold parrot
#

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

unreal zinc
#

hm okay. tbh this seems like a mess but i guess most game engines are

cold parrot
#

its also a common practice to keep vendor assets (art mostly) in a separate root level folder

cold parrot
#

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

unreal zinc
#

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

cold parrot
#

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

unreal zinc
#

mmmm describing MVC as 'really invasive, opinionated' is highly accurate lol

cold parrot
#

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

true palm
#

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?

cold parrot
true palm
#

The sprite versus the first person view

unreal zinc
#

i see why you want to change it but it kinda looks cool tbh

true palm
#

it does but it just totaly obscures the crosshair so when you ads you cant even see the iron sights

warm wren
true palm
warm wren
# true palm 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

true palm
#

ok

warm wren
#

You could also just disable the mesh renderer instead of the whole game object

true palm
#

ok

vale wren
#

heard the latter had some security stuff, not sure what it is, but also not sure if it's been fixed

plucky karma
#

Wait, facepunch offers network solution? I thought they have been using steamworks.net all this time? (I'm thinking of gmod?)

potent sleet
#

I think facepunch made the steamworks plugin for c#/unity

#

bu yeah same facepunch from gmod lol

void basalt
#

They made one of the hundred wrappers that exist for steamworks

#

unlikely you're going to be making a multiplayer game with just that

potent sleet
#

ya wrapper there ya go

void basalt
#
        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.

potent sleet
void basalt
#

yeah

#

changed that already

#

oh wait

#

no I didnt

potent sleet
#

lol

daring dust
#

it says "myRigidbody of birbscript is not assigned." Hlep me.

somber nacelle
#

have you dragged a reference to the Rigidbody2D in the inspector?

daring dust
#

oh, somehow i missed that part in the tutorial, ty

wary shadow
#

Why does this happen? Its all 0 when it's in vector form but not 0 when taken out individually..

tawny elkBOT
#
Posting 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.

wary shadow
quartz folio
#

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

mellow sigil
#

Those are very small values close to zero so they get rounded when printing the vector

unreal zinc
#

1.22E-12 is 0.00000000000012 i think

wary shadow
#

But the values are zero in the inspector.

unreal zinc
#

right, because it's showing you a rounded off number I think

wary shadow
#

So if we set the rotation of a game object zero. Its not actually zero? That doesn't make any sense.

unreal zinc
#

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

fervent furnace
#

1.22E-12 i think this only exists in double….

#

Is floating has such precision?

mellow sigil
#

Smallest float is somewhere around 1E-38

unreal zinc
wary shadow
#

These are the values in the inspector.

mellow sigil
#

no wait, that's the smallest negative value

unreal zinc
#

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)

fervent furnace
#

Oh my fault, single can represent 12e-12 by just setting the mantissa and exponent

wary shadow
fervent furnace
#

Impossible ,compare two floating or double usually |a-b|<threshold

somber nacelle
#

unity conveniently has Mathf.Approximately to compare floats

fervent furnace
#

Or you just you two integers to represent a rational fraction….

#

But you should compute the simplified fraction each time

wary shadow
somber nacelle
#

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

unreal zinc
#

What's the actual problem though? Are you getting visual artifacts? Z-fighting?

drifting fog
#

Is there a way to combine meshes using AcquireReadOnlyMeshData and jobs?

wary shadow
somber nacelle
#

what is the issue anyway?

wary shadow
#

I wanted to divide the value of x with another float. So theat was giving me wierd answers.

somber nacelle
#

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

plush sparrow
#

How should I store data in Android application to maintain privacy and prevent the user from altering the data?

somber nacelle
#

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

plush sparrow
#

So like in only offline games
There's no better options than hashing or encrypting the data?

potent sleet
#

the best imo is always a server

plush sparrow
#

That makes sense

#

I will look into sqlcipher

#

Thanks

ocean river
#

can i get support for unity for 3ds here?

#

i mean the nintendo 3ds
thats a thing

somber nacelle
#

pretty sure there are dedicated forums for that since nintendo is pretty strict about its NDAs

ocean river
#

and where are these forums

#

all i get is 3ds max and 3d

potent sleet
#

goodluck getting the nintendo unity version

ocean river
#

got it already

#

i mean, i would be asking

#

i just cant get the font to work on 3ds

somber nacelle
# ocean river and *where* are these forums

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 πŸ€·β€β™‚οΈ

ocean river
#

thanks for the help tho

plush sparrow
#

Does unity playerprefs and Android sharedpreferences do the same thing?

plucky inlet
#

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! πŸ™‚

elder temple
#

How can I limit character typed in ui inputfield to 5?

swift falcon
plucky inlet
#

woops, you replied πŸ˜„

vale spade
#

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);
        }
    }
thin aurora
#

Like, what does the code do right now that is wrong?

vale spade
#

the balls still collide

#

they dont pass trough each other

#

(sprite is a bit smaller than the collision box

thin aurora
# vale spade the balls still collide

Let's debug the code process first.

  1. Is OnCollisionEnter executed at all? You can place a Debug.Log down at the start of the method to verify.
  2. Is if (collision.gameObject.name == gameObject.name) passed? You can place a Debug.Log($"{collision.gameObject.name}, {gameObject.name}"); down before the if-statement to verify the names of the gameobject and check if they are equal.
vale spade
#

is the $"" similar to f"" in python ?

thin aurora
vale spade
#

cool, i love that feature

#

Ah ur right the collision isnt triggered

thin aurora
#

I notice the game is in 2d?

vale spade
#

yes it is

thin aurora
vale spade
#

doest the collision btw work if i dont have 'is trigger' enableD ?

thin aurora
#

I think so

#

Try it and see β„’

vale spade
#

the debug works now

#

I'd assume i also need Physics2D instead :d

thin aurora
#

Collision2D yes

vale spade
#

hhmmm

#

Issue now is, it still collides the on the first frame

#

and then adds ignore collision and ignores its henceforth

thin aurora
#

I'm guessing Unity adds the exception on the next frame

vale spade
#

yeah can imagine, better sollution would be to find all other balls in start and adds the ignore collision

hollow kernel
#

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

hollow kernel
hollow kernel
#

thanks

vale spade
thin aurora
#

I don't think they need to exist in the scene?

vale spade
#

Im spawning an unspecified number of balls in

#

and they have a limited lifetime

thin aurora
#

I see

vale spade
#

so the list is gonna limited to 100ish balls

soft shard
# hollow kernel the overlap circle is supposed to be this much but it is more than that for some...

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

GitHub

Debugging Utilities for Unity. Contribute to vertxxyz/Vertx.Debugging development by creating an account on GitHub.

hollow kernel
#

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

hollow kernel
#

ok i have figured out my issue thank you so much

the gizmos helped!

steady valve
#

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.

thin aurora
steady valve
#

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

worldly zealot
#

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?

worldly zealot
uncut plank
red scarab
red scarab
winged mortar
# worldly zealot i have a multiplayer game and everything is supposed to start in the menu scene ...
GitHub

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

polar marten
#

if you can avoid it, don't use scenes

frosty creek
#

finite state machine

plush sparrow
#

Does unity player preferences and Android shared preference do the same thing?

tawny elkBOT
#
Posting 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.

wheat cargo
upper hinge
#

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

hot torrent
#

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?

hot torrent
#

?

simple egret
#

Yep a simple null check will do. Unity has overriden the == operator to also check for the destroyed state of the objects.

hot torrent
#

mhm, alright, let my try!

hot torrent
simple egret
#

Same thing, when you override ==, compiler enforces that != is also overriden

plush sparrow
upper hinge
simple egret
potent sleet
#

Contains

hot torrent
#

?

simple egret
#

Yes, for the null check. But no, since you're modifying the list you're iterating on with foreach

potent sleet
#

^

simple egret
#

You should use a reverse for loop to pop elements from the end

potent sleet
#

use a for loop to modify list

hot torrent
#

whut? ._."

simple egret
#

If you run this code you'll get an exception

#

Collection was modified, enumeration cannot continue
Or something

potent sleet
# hot torrent whut? ._."

whut and question marks are kinda bad responses.. You should ask what exactly you're confused on..

plush sparrow
potent sleet
#

Binary

simple egret
#

Files, dedicated app storage

plush sparrow
#

I am being told that's not secure

potent sleet
#

Binary files aren't easy to read for regular joes

plush sparrow
#

And it's slow to save in external memory

potent sleet
#

if the game is offline why do you care if it's modified

hot torrent
potent sleet
simple egret
# plush sparrow And it's slow to save in external memory

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

hot torrent
#

so then how would i do it?... without referencing it...? or what is going wrong?

simple egret
#

You do it with the reverse for loop

potent sleet
hot torrent
#

wait, lemme think!

simple egret
#

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!

potent sleet
hot torrent
#

so this goes over the list in reverse?...

potent sleet
#

pretty much

hot torrent
#

but why go over it in reverse?

#

and not,,, forward?

potent sleet
#

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

simple egret
#

When you Remove an element, all the following elements shift right so they take the empty space

hot torrent
#

isn`t that good?

simple egret
#

If you iterated forwards, then you would start skipping elements as the loop doesn't account for the shiftings

hot torrent
#

so this is how i should do it?

hot torrent
#

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!

simple egret
#

You'll notice now that your scoreboard text is backwards, probably, as the thing is now fully reversed

hot torrent
#

oh

simple egret
#

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

hot torrent
#

what will it remove then?...

#

oh right...

#

nevermind

spiral geyser
#

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)

tall kettle
#

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?

tall kettle
spiral geyser
potent sleet
#

if you're using rigidbodies you def need joints πŸ™‚

tall kettle
#

im gonna try putting one interactable in the other and see if i can still grab it how i want it to work

polar marten
#

there are really good ones

#

like VR Interaction Toolkit

tall kettle
polar marten
#

maybe carefully read the docs

polar marten
tall kettle
#

well not in C#

potent sleet
#

start from the basics

elder hollow
#
    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

oblique spoke
rigid island
leaden ice
rigid island
leaden ice
#

Pretty sure I just explained it πŸ˜‰

#

The only difference is you replace the neighbors() function with one that only returns the northest/northwest neighbors

rigid island
#

AH Ok I will try that

rigid island
#

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(),
        };
    }```
fervent topaz
#

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

leaden ice
#

so you can the search method

rigid island
#

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 πŸͺ¦

winged mortar
#

Help with navmeshagent early stopping

rigid island
#

@leaden ice I got it working ! thanks again for the suggestion
List<Vector3Int> Search(Vector3Int start, int maxDepth, Func<Vector3Int, Vector3Int[]> neighborFunc)

fair sierra
#

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;
    }```
leaden ice
#

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.
fair sierra
#

Okay, thank you very much! I think I will go by the list because in my opinion the code is to circuitously anyway

winged mortar
#

Does every row have the same amount of children?

#

@fair sierra

fair sierra
#

yes

winged mortar
#

Then you could, if you wanted to, really simplify your code want some help?

fair sierra
#

im not shure if later on the amount of children per row could vary

#

but still thank you

winged mortar
#

Got it, you can probably do this in a single line of code though =p

#

Look into IEnumerable.Select() and IEnumerable.SelectMany()

fair sierra
#

iΒ΄ll definitely do that, thanks

broken trail
#

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

sterile tendon
#

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

fast wraith
#

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?

polar marten
polar marten
#

it will still be slightly off

sterile tendon
#

yeah I realized afterwards

polar marten
#

you should use an asset for sequencing audio or research it more

sterile tendon
#

yeah I found a tutorial for it I'm using now

strong cloud
sterile tendon
polar marten
#

you can also try the unity timeline which specially treats audio sequencing

#

you can use playablegraphs too

upbeat carbon
#

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.

vapid patrol
#

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

red scarab
vapid patrol
#

but it doesnt work when i rotate on the y axis

red scarab
red scarab
vapid patrol
#

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);
     }```
red scarab
#

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?

vapid patrol
#

lemme record a vid

upbeat carbon
red scarab
vapid patrol
#

tilt is exaugurated so u can see it better

red scarab
# vapid patrol

it looks smooth to me... you mean when going from left to right, it's a very sudden jerking motion?

vapid patrol
#

when i go right and let go its ok but when i switch immediately it doesnt smooth

vapid patrol
upbeat carbon
red scarab
vapid patrol
#

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);
 }

}```

red scarab
#

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 ^

vapid patrol
#

ok wait

#

colors πŸ‘

red scarab
#

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

vapid patrol
#
 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?

red scarab
#

thats better lol. colors

vapid patrol
#

yay

vapid patrol
#

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

agile lynx
#

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?

polar marten
agile lynx
#

A generic state machine that works for every enemy entity (maybe even the player itself)

pale shadow
#

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?

oblique spoke
pale shadow
#

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?

leaden ice
pale shadow
oblique spoke
pale shadow
leaden ice
oblique spoke
#

Small amount of data saves and loads very quickly

grave crane
#

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?

leaden ice
gleaming sparrow
#

maybe change script load order priority from the project settings? idk

proven plume
#

Hi guys let s see if you can help me out

fast wraith
#

Hah. I had to right click the incompatible assembly in the solution and reload it manually.

fathom geode
#

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?

fathom geode
#

wouldn't that update just as often as the main thread? or do I use waitforseconds and have the coroutine restart itself?

gleaming sparrow
#

yeah you can use a waitforseconds to delay it and let it repeat every so many seconds

void basalt
#

I've never used them, so someone else will have to verify.

fathom geode
#

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)

void basalt
#

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

fathom geode
#

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

void basalt
#

Ensure that you're not running everything in update()

fathom geode
#

ofc

void basalt
#

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.

fathom geode
#

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

void basalt
#

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

fathom geode
#
 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?

void basalt
#

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

fathom geode
#

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

void basalt
#

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.

sly nacelle
#

I need help with changing to a layer on a gameobject that effects the children

gleaming sparrow
#

U want to change layer and have all children change with it?

#

Does this need to happen at runtime?

sly nacelle
#

yes and yes

#

I have a script to change one gameobjec but I dont want to apply it to all the gameobjects

gleaming sparrow
#

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

sly nacelle
#

damn

#

this is what I have rn

#

if (other.gameObject.CompareTag("Light"))
{
gameObject.layer = 3;

    }
gleaming sparrow
#

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);
    }
}
gleaming sparrow
inland escarp
#

Is there anyway to get around the vector3 doesn’t accept doubles thing?

sly nacelle
gleaming sparrow
sly nacelle
#

oh lol

inland escarp
#

Doesn’t that convert to float?

buoyant crane
void basalt
#

Vector3 only accepts float

gleaming sparrow
#

And int i think

void basalt
#

Are you doing something that requires double precision?

#

if not then dont

edgy lynx
#

yea most likely would never need a double really, unless idk Kerbal Space Program. 🀷

inland escarp
void basalt
#

Unity's simulation only uses floats

#

the second your numbers get plugged back into unity, they're floats

inland escarp
#

That seems useful thank you

buoyant crane
inland escarp
buoyant crane
#

yeah should reduce most of the imprecision UnityChanThumbsUp

sly nacelle
void basalt
gleaming sparrow
#

Just do β€˜transform’

sly nacelle
#

I dumb

gleaming sparrow
#

πŸ™‚

#

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

sly nacelle
#

maybe

buoyant crane
# sly nacelle

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.

sly nacelle
#

I did it was a mistake

#

it works

gleaming sparrow
#

Nice

pale shadow
#

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?

buoyant crane
pale shadow
buoyant crane
pale shadow
#

OH

kindred sparrow
#

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.

inner oar
#

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

leaden ice
#

Assigning in the inspector is the preferred method.

#

But transform.Find and transform.GetChild etc should work fine, generally

buoyant crane
inner oar
# leaden ice Assigning in the inspector is the preferred method.

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?

leaden ice
kindred sparrow
#

I want the name of the object being hit so that I can use it to change its position

buoyant crane
kindred sparrow
#

Yes

#

I’ve done it just fine

#

But it doesn’t stay on if that makes sense

buoyant crane
#

it doesn’t sound like you need to store the name, just the transform

kindred sparrow
#

Idk, I need to get the transform to happen continuously

leaden ice
kindred sparrow
#

Because the object of which I’m changing is not the one containing the script

leaden ice
#

You just need a reference to the Transform

leaden ice
#

Learn to work with references in C#