#archived-code-general

1 messages · Page 196 of 1

somber nacelle
#

that was in response to Fen, not you. but you're also way out of date for a 2022 release

thick socket
#

I can reference it in scripts and have no issues

heady iris
#

I'm on 2022.3.10f1 at the moment and the checkbox won't appear with no methods defined.

#

It also won't appear with just Awake defined.

thick socket
somber nacelle
heady iris
#

I'll have to look when I go back onto 2023.x

#

(i'm using an LTS release for once in my life)

thick socket
#

still can't enable/disable it

#

removing and adding the script again doesn't fix either

heady iris
#

Double click the "Script" field on that component. See what file opens.

thick socket
#

of course the asset author has 2 scrips here with the same name

#

why not 😄

heady iris
#

That'll do it.

thick socket
#

adding update to that one lets you enable/disable it

heady iris
#

Pick the right one from the list when adding a component.

gleaming vessel
#

Can you give me an example of how I could contact a current script and function on the website?

heady iris
#

(or just rename their asset)

#

I suppose you'd also need to rename their class afterwards.

#

but if both classes are in the global namespace, then one class must have a name other than Monster already

somber nacelle
heady iris
#

Pretty sure this is 2023-exclusive?

thick socket
#

different namespaces

heady iris
#

ah, okay

#

then you'll just have to watch out for that

thick socket
#

works now thanks 😄

#

weird thing is

#

I used the correct namespace when importing once

#

and I still couldn't drag it in

knotty sun
thick socket
#

How much worse performance is using a polygon collider with like 40 points over a box collider (2d)

#

If Im making a small mobile game Im guessing it doesn't really make much difference

somber nacelle
#

most performance related questions can be answered with a simple "It Depends™️"
use the profiler to diagnose and check for performance issues

gleaming vessel
thick socket
knotty sun
thick socket
#

putting a polygon collider on "EnemyGrimReaper" doesn't actually "fit the shape"

#

any idea why that doesn't work

somber nacelle
#

you didn't customize its physics shape in the sprite editor

thick socket
#

I get that the renderers are children but that should'nt matter?

somber nacelle
#

actually i'm not even sure if a polygon collider will automatically work with a setup like this. i don't typically use bones to animate my sprites, i use good old fashioned sprite sheets so 🤷‍♂️

#

either way not a code question

thick socket
#

just a lot of children with sprites on it

#

where should I go for this kinda Q tho

gleaming vessel
somber nacelle
knotty sun
gleaming vessel
#

yep

knotty sun
#

My code

    // Send a Message to a Unity GameObject/Method
    S4U_sendmessage : function(method, str) {
        //_S4U_log('sendmessage to '+S4U_data.go+'.'+method+' '+str);
        if (S4U_data.go != null && method != null) {
            if (str == undefined) {
                SendMessage(S4U_data.go, method);
            }
            else {
                SendMessage(S4U_data.go, method, str);
            }
        }
    },
#

this can be called from javascript, needs a gameobject name and a method for it it work

gleaming vessel
#

is it the same code?

gleaming vessel
knotty sun
#

tells me nothing

gleaming vessel
# knotty sun tells me nothing

when I start the game on website, website catches an event from unity but when he use SendMessage("WebManager", "SetInitialData", JSON.stringify(unityData), nothing is called in Unity

gleaming vessel
knotty sun
gleaming vessel
# gleaming vessel

@knotty sun There you can see "123" logs that means the event "getIntialData" came from unity and when my friend use SendMessage nothing come in unity and I don't know how to check where is an error from my side or from his side

knotty sun
#

post your jslib to a paste site

simple spire
#

just for information, Unity don't have an option for really avoid agents bumping into each others

thick socket
#
NullReferenceException: Object reference not set to an instance of an object
Fighter.SetStates (UnityEngine.Vector3 _currentVelocity) (at Assets/Scripts/Enemy/Base/Fighter.cs:108)
EnemyMonster.SetStates (UnityEngine.Vector3 _currentVelocity) (at Assets/Scripts/Enemy/Base/EnemyMonster.cs:36)
Fighter.JumpsandChecks (UnityEngine.Vector3 movement, System.Boolean jump, System.Boolean down, UnityEngine.Transform target) (at Assets/Scripts/Enemy/Base/Fighter.cs:92)
EnemyCharacter.MoveEnemy (UnityEngine.Vector3 velocity, System.Boolean jump, System.Boolean down) (at Assets/Scripts/Enemy/Base/EnemyCharacter.cs:82)
EnemyIdleStandStill.DoFrameUpdateLogic () (at Assets/Scripts/Enemy/Behavior Logic/Idle/EnemyIdleStandStill.cs:31)
EnemyIdleState.FrameUpdate () (at Assets/Scripts/Enemy/State Machine/ConcreteStates/EnemyIdleState.cs:32)
EnemyCharacter.Update () (at Assets/Scripts/Enemy/Base/EnemyCharacter.cs:63)
#

any idea which line is actually the issue?

#

I've tried debugging like 10 variables and having none be null so far

knotty sun
#

Fighter.SetStates (UnityEngine.Vector3 _currentVelocity) (at Assets/Scripts/Enemy/Base/Fighter.cs:108)

thick socket
#

thanks

#

tried to override that function but still called the base on accident 🤦‍♂️

thick socket
knotty sun
#

nope

thick socket
#

weird

knotty sun
#

Unity

heady iris
#

I've had problems with that. It takes you one frame back in the callstack

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.

spring creek
#

Rather than calling the bot again, you could have just looked at the one you called in the other channel. Just fyi

turbid salmon
#

please don't report mods

knotty sun
turbid salmon
#

ok

rigid island
knotty sun
#

The code, like all GPT code is crap

rigid island
#

was about to say same..

#

those comments usually a dead giveaway lol

turbid salmon
#

yes i said to chatgpt to fix my script ok

knotty sun
#

worse thing is, the one who posted it has no idea

knotty sun
turbid salmon
#

forgive me

knotty sun
#

no

#

you have been told multiple times before

thick socket
#
private void OnCollisionEnter2D(Collision2D collision)
    {
        var tag = collision.transform.tag;
        if (tag == "Player")
        {
            collidingObjects.Add(collision);
        }
    }
    private void OnCollisionExit2D(Collision2D collision)
    {
        collidingObjects.Remove(collision);
    }
#
void DealDamageToColliding()
    {
        foreach (var collision in collidingObjects)
        {
            // Check if the object is still in the list (it might have been removed in OnTriggerExit)
            if (collidingObjects.Contains(collision))
            {
                Fighter colFighter = collision.gameObject.GetComponent<Fighter>();
                if(colFighter != null)
                {
                    colFighter.Damage(Mathf.FloorToInt(stats.attackDmg * 0.75f));
                    Debug.Log("damaging: " + collision.gameObject.tag);
                }
                else
                {
                    Debug.Log("Couldn't find fighter, tag = " + collision.gameObject.tag);
                }
            }
        }
    }
#

Couldn't find fighter, tag = Wall

#

It shouldn't be adding any collisions to my list unless tag = player......

#

so how is it debugging tag=wall

heady iris
#

I'm pretty sure the Collision2D you're passed in OnCollisionEnter2D gets reused

leaden ice
heady iris
#

it's a class, not a struct

leaden ice
#

I do think it's a struct though 🤔

#

oh it's a class

#

look at that

upper ice
#

Hello

heady iris
#

This claims the default is "on", but it defaults to "off"

#

so, go figure..

leaden ice
#

yeah not wise to hang onto it

heady iris
#

anyway, yeah, just store Colliders or GameObjects or something else

thick socket
#

👍

#

my character can no longer "ride" the dog lol

#

works great 😄

#

wasn't taking damage prevously lol

upper ice
#

public class CameraController : MonoBehaviour
{

public float rotateSpeed = 10.0f, speed = 10.0f, zoomSpeed = 10.0f;

    private float _mult = 1f;

private void Update()
{


    float hor = Input.GetAxis("Horizontal");
    float ver = Input.GetAxis("Vertical");
    float rotate = 0f;

    if (Input.GetKey(KeyCode.Q))

        rotate = -1f;
   else if (Input.GetKey(KeyCode.E))

        rotate = 1f;
    _mult = Input.GetKey(KeyCode.LeftShift) ? 2f : 1f;

    transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime * rotate * _mult, Space.World );
    transform.Translate(new Vector3(hor, 0, ver) * Time.deltaTime * _mult * speed, Space.Self);
    transform.position += transform.up * zoomSpeed * Time.deltaTime * Input.GetAxis("Mouse ScrollWheel");
    transform.position = new Vector3(
        transform.position.x);
    Mathf.Clamp(transform.position.y, -20f, 30f);
    transform.position.z;
}

}
Please help me, what is wrong here?

prime sinew
#

And format your code please

#

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

heady iris
warped mortar
#

This code is supposed to find a random point on the navmesh within a set radius, and make sure it isnt too close to the boss and make sure its a valid point not inside of an object

#

it worked fine before adding the Vector3.Distance if statement but now it just goes into an infinite loop and crashes my editor

#

the idea behind that if statement is to make sure the point isnt too close to the boss and to generate a new point if it is

heady iris
#

where is this code? is it in a component on the boss?

#

i'm wondering whose transform that is

naive swallow
#

Meaning it's going to skip the break again

heady iris
#

oh, duh

warped mortar
heady iris
#

you need to re-randomize the point

warped mortar
#

how could I go about doing that, cause i was wondering if continue would would make it regenerate a new hit position

heady iris
#

it would sample the mesh again, sure

naive swallow
heady iris
#

but that's not going to give you a new random spawnPoint...

warped mortar
#

because you're right I just need a new hit position

naive swallow
#

Nothing inside the for loop changes the spawn point

heady iris
#

not a new hit position. you need a new spawnPoint

#

recomputing the hit position over and over would only matter if SamplePosition behaved randomly

warped mortar
#

oh my god im so dumb 💀

#

thank you I understand what you're saying

heady iris
#

I was thinking you were comparing the distance to the wrong object

warped mortar
#

so just move that in there correct?

heady iris
#

sure

#

i would also suggest adding a "bail out" condition

#

if you try 100 times, just give up and fail

naive swallow
#

Yea what they said ^

heady iris
#

so the game won't explode if the boss falls out of the map

naive swallow
#

add in a maximum tries count

heady iris
#

you can also relax your standards first

#

so, if you tried 10 times, relax the min spawn radius, and if you tried 100 times, fail

warped mortar
#

alright thats a good idea

#

cause the issue is that when the enemy spawns too close to the boss it causes the boss to start moving which is unintended

#

cause of colliders

rocky helm
#

Not quite sure how to google this so, if I do Coroutine someCoroutine = StartCoroutine(randomCoroutine()) then what happens to someCoroutine once the coroutine reached the end, is it set to null?

heady iris
#

Objects can't really "get set to null"

#

that's just a clever trick unity pulls on you

#

a destroyed game object, for example, will equal null

#

it's still a non-null reference

#

I'm not sure if Coroutine starts equalling null after the coroutine ends

heady iris
dusky glen
#

Can anyone recommend the most popular / widely used testing options for Unity? My team lead has asked me to do some research into our options for implementing testing.

heady iris
#

nothing special happens when the coroutine is over

delicate zinc
#

i'd like some help trying to figure out this issue i'm having.

Working on a dungeong eneration algorithm, i have this setup where i'mm connecting two separate rooms, there's a sphere in the center of the two intersecting doors to represent the pivot point.

Is there a way i could calculate the required angle of rotation given any setup (first three images) so i can rotate the room so it connects correctly? (fourth image)

hard viper
dusky glen
hard viper
#

idk about automated unit testing tbh. Most of the time, you have specific failure modes in mind to test

#

unless your idea is to simulate the player putting in all manner of random inputs

#

idk if there is a tool for that, nor do I know if that is what you have in mind

turbid salmon
#

nice map !

heady iris
#

i was watching some videos about Punch-Out!! on the Wii

#

it has a "soak test" mode that just plays the entire game automatically

#

having something like that seems like a great idea (even if you have to turn on some cheats to make it happen)

hard viper
#

there might be tools to help simulate thrashing about randomly with a controller

#

ie random control stick inputs and random button inputs, and setting the relative frequency etc.

#

you’d probably be able to catch glitches where the player inputs buttons one frame apart which are otherwise very hard to see. Something the pokemon diamond remake definitely didn’t do lol

crimson ice
#

does anyone have an idea how to make a hollow gameobject?

#

like a empty 2d box

heady iris
#

I used fuzz testing to find a bunch of weird blender bugs

leaden ice
heady iris
leaden ice
#

or a polygonCollider2D in the shape of just the "hull" bit

scarlet viper
#

In games cars speed up as they drive forward on max speed, and they will drive faster/speedup as long as theyre driving fast at the moment
And I coded something similar but it doesnt take few cases into account. collisions etc.
Collisions make the car slow down/stop, but the variable responsible for tracking and storing speed growth doesnt reset on collision.

And while I could try resetting acceleration on collision I think it would be better if i based the acceleration on rigidbody's velocity in the first place but i dont have any ideas.
Anyone had similar issues?

thick socket
#
private void OnCollisionExit2D(Collision2D collision)
    {
        var tag = collision.gameObject.tag;
        if (tag == "Platform")
        {
            LeavePlatform();
        }
    }
#

is there a way to make this virtual so another class can override and add to it?

#
private void OnCollisionExit2D(Collision2D collision)
    {
        collidingObjects.Remove(collision.collider);
    }```
leaden ice
#
protected virtual void OnCollisionExit2D(Collision2D collision)```
#

and change to protected of course so child classes can access it

thick socket
#

thanks, messed it up last time so it wasn't showing "Unity Message" and thought maybe I couldn't for some weird reason

leaden ice
#

on the child class:

protected override void OnCollisionExit2D(Collision2D collision) {
  base.OnCollisionExit2D(collision); // call the parent version

  // do more stuff
}```
hard viper
coarse narwhal
#

I've no idea where the best place is to ask this, but can someone give me a heads up on the best way to test my game on my steam deck? Do I build a Linux version or Windows? How is it best to get it onto the deck? Do I need to push it to steam first or can it be side loaded? Can the steam deck be defined as a build target?

heady iris
#

I think you can push builds to the Steam Deck directly from a Windows machine.

#

I use a MacBook. I used to push builds to Itch, then go to desktop mode on my Deck to update

#

Now I have that game on Steam (not released), and I simply push to steam + update on the deck when needed

#

You should make a Linux build.

#

The Deck can run Windows builds through Proton, but Linux should be more performant.

#

The Deck isn't a specific kind of platform. It's just regular Linux.

heady iris
#

I use SuperUnityBuild to automate the build process. Pushing to Itch with it is easy. Pushing to Steam was...more annoying

#

had to do some Shell Script Hijinks

coarse narwhal
#

Interesting, thank you. I'll build for Linux, that's easy, but not too sure what you mean by "push" directly from windows to the deck. Does the build process load it onto the deck via USB, or are we talking about a more manual process of getting the Linux build and loading it onto the decks FS via some mechanism (like windows file manager) outside of the unity build process?

heady iris
#

This would be outside of Unity

coarse narwhal
#

Brilliant, thank you, that's exactly the info I was looking for!

wary mortar
#

Can somebody please help me? I'm trying to aim at a target wigh a gun, but I'm aiming with the torso. I dont know the math required to make the player aim with its gun

wary mortar
#

This is the current code, it works like a charm to aim at the target with the torso (this is Photon Quantum btw)

wary mortar
#

He is aiming with his torso, I need to make the some math equations to aim with the gun

#

I don't know how

rigid island
#

hmm looks like some custom system

wary mortar
#

Yes, the rigging asset wasn't an option

simple egret
#

Inverse kinematics for the arms will yield the best result, orient the gun (vertically) and the arms will follow automatically

wary mortar
#

change the torso's rotation to fit the gun in the aim Target

#

Isn't there some way to apply an offset?

golden garnet
#

Hey! I'm looking to make a simple top-down 2D bullet that ricochets off of a collider when they touch. The bullet should use the object's rotation to decide a random direction to bounce to. It would only bounce off in a cone of about negative 60degrees to positive 60degrees. The issue I am having is that when the bullet collides with the other collider, it ricochets in a random direction from -60 to 60, but it doesn't take into account the rotation of the collider-- meaning it only travels upwards in a random direction from -60 to 60. Here is the function I am using. Where am I going wrong?

    {
        Debug.Log("Bullet Ricocheted!");
        float randomFloat = Random.Range(-60f, 60f);
        Debug.Log(randomFloat);
        Vector3 ricochetDir = new(umbrella.gameObject.transform.rotation.x, umbrella.gameObject.transform.rotation.y, umbrella.gameObject.transform.rotation.z + randomFloat);
        gameObject.transform.rotation = Quaternion.Euler(ricochetDir);
        rb2d.velocity = shootSpeed * transform.up;
    }```
#

The random float is the random modifier for the bullet's z direction. See how the vector3 gets the z rotation added to the randomFloat? Right now, it's almost as if it doesn't take in the current rotation of the other collider, or "umbrella", at all

leaden ice
#

oh no

#

you've made a terrible mistake here

#

transform.rotation is a Quaternion. It is not a set of euler angles

golden garnet
#

uh oh

leaden ice
#

you cannot read .x and .z and .y from it and expect those to be the rotations around those axes

#

that's not how quaternions work

golden garnet
#

ah okay

#

shoot lol

leaden ice
#
Quaternion umbrellaRot = umbrella.transform.rotation;
Quaternion randomChange = Quaternion.Euler(0, 0, randomFloat);
transform.rotation = umbrellaRot * randomChange;

Try this @golden garnet

golden garnet
#

Okay, gimme a sec

leaden ice
#

* is used to basically "add" quaternions

#

so we're just making a random z rotation quaternion and adding it to the umbrella's rotation

golden garnet
#

Wow, you're a life saver for real

#

Thanks, I really appreciate it. I'll have to look into Quaternions more i guess 🫠

leaden ice
# golden garnet Thanks, I really appreciate it. I'll have to look into Quaternions more i guess ...

They're actually incredibly simple to work with. Don't make the mistake that most people make of trying to understand the math behind them. Just think of them as variables that represent a rotation. From there you just need to understand the APIs which let you create them from various parameters, and that you can combine them with * (a * b applies a first, then b), and you'll be wielding them like a master in no time.

modern creek
#

I am doing some level design on my grid and it's difficult to see where I am on the grid. Is there an .. object or something I can drop in my scene that has no effect in game? Like a .. manual gizmo?

severe gale
#

is there voice channels on this discord ? if so where?

severe gale
#

dang

#

see ya then

unique thunder
#

Hey guys, I’m making a csr2 style game with a career mode. My current plan is have a tournamentCompleted and tournamentRacesDone variable saved to the json. Each tournament has 5 races so once tournamentRaces hits 5 I’ll have it set to 0 and tournamentCompleted++. Is this the best way of setting something like this up?

leaden ice
#

¯_(ツ)_/¯

sullen fern
#

im making a 3d action game and im thinking of making the enemies circle around the player before attacking but im not sure wha the best way to do it is

#

its gonna be a humanoid enemy so i cant really use rotate it around the player cause itd look unnatural

#

is there some way i might be able to use navmesh?

unique thunder
cosmic rain
#

Or create a path manually.

sullen fern
#

like rotate the destination vector around the player?

unique thunder
#

Just wondering if an implementation like that would work. I have a coding background but have never used it for something such as a career mode. Just making sure before so I don’t waste time with it

leaden ice
#

What wouldn't work about it

unique thunder
leaden ice
heady iris
#

Is there something you are worried about in particular?

#

like, say

#

player save files being messed up after you update the game?

unique thunder
heady verge
#

hey there, thank you for awnser (was not at home anymore at this time) i dont understand what to do with this "Physics.queriesHItTriggers"

Documentation just say: "Static bool"
How to use this ?

cosmic rain
heady verge
#

Documentation is so fantastic much useless.
surly: 1 singel code example, they will die...

cosmic rain
cosmic rain
heady verge
cosmic rain
#

I don't think there were any relevant changes between these 2 versions.🤔

frigid glen
#

How do you inline a variable into an if statement?
So from this:

float distance = math.distance(enemyTransform[enemyIndex].Position, towers[towerIndex].Location);
if (distance < towers[towerIndex].Range)
{
    //Whatever
}   

to something like this?

if (ref math.distance(enemyTransform[enemyIndex].Position, towers[towerIndex].Location) < towers[towerIndex].Range)
{
    //Whatever
}   
cosmic rain
#

And no clue what you mean by lost coding.😅

cosmic rain
heady verge
cosmic rain
frigid glen
#

theres no point if u cant inline the entire thing

heady verge
cosmic rain
heady verge
cosmic rain
frigid glen
heady verge
heady verge
cosmic rain
frigid glen
cosmic rain
#

Here's a tip: if it's difficult to express your thoughts in English, use translation tools, like google translate.

heady verge
heady verge
frigid glen
#

eh forget it, Ill just make a variable and use it twice

cosmic rain
cosmic rain
heady verge
cosmic rain
heady verge
cosmic rain
#

Wrong message referenced then. It's okay. Anyways, if you need proper help, you've got to make sure that the "helpers" can understand you.

pure portal
#

hello i want to ask on how to utilize await function best
so i have an async method that return a value
this method will be called in another method
but because it's an async method it will infect the other method that use it
is there anyway to work this better?

cosmic rain
#

"infect"?😅

pure portal
#

haha if i call an await method in a normal method there will be an error of
"the 'await' operator can only be used within an async method"
so it will 'infect' the normal method to also become async method

cosmic rain
#

Why would you use await in a normal method?

pure portal
#

it's a work around of a small project test
the actual script none use await function because all data is from resource
but now i am trying to change on how they access the data to entirely online in which why i need to use await function in several method
so i try to not change the main script as much as possible

#

the main script only need to get a list of string which called from a return method
now i try to get this list of string online which need an await function

cosmic rain
#

Wdym by "online"? And why does that require await?

#

Do you mean like awaiting a web request?

pure portal
#

yup

cosmic rain
#

Well, you don't need to use await. In fact, you can't as the error suggests.

#

If you want to block the main thread until the async method is complete, you can access the task's Result.

pure portal
cosmic rain
#

I'm not sure about unitask. I was assuming you're using regular tasks.

#

Might want to read their docs.

pure portal
#

hmm ok thanks
will try

cosmic rain
#

Seems like they have a GetAwaiter. Could get the awaiter and call GetResults on it.

#

Though it seems like they warn about not using it for some reason.🤔

pure portal
#

haha i tried several things with the await function and sometimes my editor is not responding when played

thin aurora
#

If Unity supports it, you can fake it with pattern matching

#

if ("This is a string" is string myString && !string.IsNullOrEmpty(myString)) {}
But I am pretty sure that the pattern matching does not allow assignment in Unity (yet).
Other than that, this is not a question fit for this channel and you should have just Googled it.

cosmic rain
tacit vine
#

So i have a interface with the following code

#

because the GenerateGUID is always the same

#

but this does work in the same C# version as unity but it doesn't work here?

#

i mean i cant call the function like this

#

or this

flint kettle
#

I am making a character controller, and I have a question.
What's different between transform.Translate and transform.position in moving character?

split condor
#

Hello i have the following code to teleport one object to another while selected but sometimes it's just stop working, when the object teleport to a location after some time no matter how much i click on it the system doesn't see me clicking the object anymore, i tried everything, change layer, colliders, etc... but still the same issue, does someone know an alternative to this please?

somber nacelle
heady iris
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.

heady iris
#

also, just a sanity check for preventing memory leaks

#

if I have an object with an event on it that has subscribers, it can still get GC'd, right?

#

as long as nobody can reference it

leaden ice
#

the subscribers cannot be GCed

heady iris
#

right

#

I have an object that represents a quicktime event. When it starts, it subscribes to events on the brains of the entities that are involved

#

wait, I had this backwards in my head

#

i was thinking the brains were subscribing to the QTE's event for some reason

#

ok this obviously won't clean up by itself

#

I'll just have the QTE object unsubscribe itself when it terminates.

#

i need Coffee

gilded kelp
#

Hi guys,

I'm having problem using new Unity input system.

  1. i have pan toool which is using left mouse button
  2. rotate tool which is using alt+left mouse button.

So when i do alt+leftMouseButton then it also triggers pan tool which should not happen.

heady iris
#

there's an option for this

#

"Enable Input Consumption"

#

project settings -> input system package

#

it causes more specific bindings to "consume" the input, completely skipping less specific bindings

static matrix
#

whats a good way to get an item to work similar to a spear in rain world (in 3d), where upon hitting an object it sticks to it?

heady iris
#

on collision, make your rigidbody kinematic and parent yourself to the thing you hit

static matrix
#

good idea

heady iris
#

or just turn the rigidbody off entirely, possibly

#

er

#

you can't turn off a rigidbody, right

#

I'm thinking about potential problems when sticking to another moving object

static matrix
#

you could always remove the component ig

heady iris
#

an enemy might start banging into the spear

#

disabling your colliders would do the trick

static matrix
#

fun

gilded kelp
#

@heady iris Thanks i just enable the input consuption. now again it triggers pan tool when i release the left mouse button.
Following questions.

  1. I'm using InputActionReference so it doesn't continously print's out the debug of action performed. to achieve this do i have to use update and use boolean like when mouse pressed boolean becomes true and on cancelled boolean becomes false and underlying code perform?
heady iris
#

you can call actionRef.action.IsPressed()

thick socket
#

if my enemy.target stores the transform of say player.center

#

then in another code I do
Transform target = enemy.target

#

and then change say
target = chest.center

#

is the enemy.target now equal to chest.center?

#

95% sure it wouldn't change the enemy.target but figure I doublecheck 😄

rocky helm
thick socket
#

I dont understand why its always shooting the farthest target and then also never switching

#

Its supposed to shoot closest target that it has Line of sight to

#

if no LOS then closest target

#

jumping around or moving throughout scene doesn't change that it always shoots the initial target

#

no where else in code does it change target

#

Debug.Log shows that the enemylist is indeed 2 so it also has both enemies to start

#

The platforms shouldn't be hit with the raycast

#

I've tried jumping near and above them to switch target to no success either

south violet
#

Hey, I try to write a test that checks whether an exception is thrown by Awake() method, but for some reason Assert does not catch any exception and test fails and anyways I get an error that exception was thrown. How can I do that properly?

On the screen there 2 Asserts I tried with

hoary mason
#

Btw one question

#

How do you do grid movement that can respond to collisions?

static matrix
#

you would have to self-build cols id think
like whenever something tries to move it first checks if an object with a collider is in the tile

leaden ice
leaden ice
thick socket
#

Hurray Praetor is here!

thick socket
# thick socket

Just didnt see anyone super smart thats also helpful online and I couldnt figure out my issue myself 😦

#

Guessing I made some smol dumb mistake that I cant see

hoary mason
jaunty needle
#

Hey guys, how does the unity Ray struct work?

hoary mason
#

Like say with pokemon

jaunty needle
#

Like what is it made of

leaden ice
#

As for navigation - use standard graph navigation algorithms like Djisktra's and A*

deft timber
jaunty needle
deft timber
jaunty needle
#

hmm

hoary mason
#

Aaah

#

I see

jaunty needle
#

no source code ig

late lion
jaunty needle
#

my god until now I didn't realize you could put methods in structs

torpid hawk
#

I have a quiz app in unity I make the code but when I clicked any answer its always wrong can you help me

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

south violet
#

@leaden ice So yeah, Im expecting to catch NullReferenceException, but in the end its not being caught and its thrown anyway xD

leaden ice
# south violet

it's cut off - which line is this happening on in the test class?

gleaming imp
#

have this error:

error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?)

thought this was the solution

You need to add the namespace UnityEngine.UI to the top of the of your script, this is the namespace that the type Image exists in.

but the namespace is added and error continues. any ideas?

rigid island
#

you could try regen project files

heady iris
#

show what you wrote

rain minnow
gleaming imp
#

how do you regen

rain minnow
#

did you lose configuration (connection) with unity and your IDE?

rigid island
gleaming imp
#

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

rigid island
#

alr

heady iris
#

okay, that's fine.

#

i'd just close and reopen my code editor first

#

occasionally VSCode's language server falls over and dies

rich lily
#

is there like docs or forums where a beginner can learn about C# in unity?
a lot of the time I find myself looking at youtube tutorials
but idk if that's the best way
with c++ it certainly wasn't

heady iris
#

well, !learn will teach you some basic concepts

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

rain minnow
rigid island
#

crosspost

#

ah

heady iris
gleaming imp
rigid island
heady iris
#

ah, yes, this is mangled

#

!ide

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

gleaming imp
#

huh

rigid island
#

follow the bot msg

gleaming imp
#

i need a plugin for jetbrains

#

to work with vs code?

rigid island
#

no

#

which one you have VScode or Rider?

#

just get the Unity extension in VScode

gleaming imp
#

i have vs code

rain minnow
dense vessel
#

Hello!
I'm trying to use streams from different threads but I can't find a way to make it safe.
Basically, one thread can write to the stream using a StreamWriter and the main thread must Debug.Log() what's added to the stream by the thread.

Initially, I was using this to read the new data (where consoleStream is the Stream and consoleReader a StreamReader associated with it) :

if (consoleStream.Length != oldLength){
  consoleStream.Seek(oldLength, SeekOrigin.Begin);
  oldLength = consoleStream.Length;
  Debug.Log(consoleReader.ReadToEnd());
}

But then I figured it probably isn't thread safe if the other thread tries to write to the stream at the same time 🤔 Am I right about this? And if so, how could I make it thread safe without modifying the code to write to the stream (I don't control that code)?

To give more context, I'm executing runtime compiled C# code in a thread and I'm trying to retrieve the output (so for example if the code uses Console.WriteLine, I want to Debug.Log what was printed). For this I use Console.SetOut(), which makes Console methods write to a stream instead of a console.

leaden ice
#

so it might already be threadsafe

dense vessel
#

Thank you, I'll look at this !

fervent furnace
#

dont know about much on c# stream, assume you havent synchronized your stream, this is not thread safe and one thread write, one thread read
if stream length increase after oldlength=stream.length, you will still enter the if statement next round but seek start from oldlength, and debug.log some words that are already printed

#

i think you should use concurrency queue, but you cant change your code.....

gleaming imp
#

ok so... i followed the instructions, but error persists. vscode was already opening my files before.

#

i did the config, regen, nothing changed

dense vessel
gleaming imp
#

I´ve had this error hapen before with old assets using outdated API and I had to change some variables or add namespace

#

but now I can´t figure out what´s wrong

mighty ivy
#

Hi! I'm trying to merge two lists of NavMeshBuildSource: one is a list and another is a list derived from a dictionary (so a list of KeyCollection of which the keys are NavMeshBuildSources). I initialize the list from the list of pair collections with this line of code: List<NavMeshBuildSource> mergedSourcesList = new List<NavMeshBuildSource>(obj.source2); where obj.source2 is a list of type public Dictionary<NavMeshBuildSource, GameObject>.KeyCollection source2;. This works perfectly well, until the list is too big and it crashes with this exception: System.ArgumentException: Destination array is not long enough to copy all the items in the collection. Check array index and length.
at System.Collections.Generic.Dictionary2+KeyCollection[TKey,TValue].CopyTo (TKey[] array, System.Int32 index) [0x0002a] in <787acc3c9a4c471ba7d971300105af24>:0 at System.Collections.Generic.List1[T]..ctor (System.Collections.Generic.IEnumerable`1[T] collection) [0x0003b] in <787acc3c9a4c471ba7d971300105af24>:0
at NavMeshCarver.MergeSourcesThread () [0x0002f] in D:[...][the place where the list is initialized as shown above.]
UnityEngine.Debug:LogWarning (object)

#

What can I do to avid this exception? It seems like the keyCollection is being initialized in a list that is too small to contain all of the keys. I've never encountered such error

static matrix
#

when a navmeshsurface bakes does it bake everything in the scene or just the things that it parents

#

(you may recall my pathfinding issues from earlier)

leaden ice
#

hoiw about just:

mergedSourcesList = whateverDictionary.Keys.ToList();```
static matrix
#

basically, can I have one navmeshsurface in the scene and just ocassinally rebake it
and that'll do pathing

mighty ivy
# leaden ice hoiw about just: ```cs mergedSourcesList = whateverDictionary.Keys.ToList();```

Can't do it - it's being done inside a thread and the dictionary is constantly being modified by the main thread (and sometimes by other threads, in a safe way). What the main thread do to avoid causing problem is creating a copy of the keys and simply pushing it in a ConcurrentQueue list, taking a "screenshot" of the dictionary's keys the moment the build nav mesh method gets called

leaden ice
#

which is probably the root of your problem

mighty ivy
#

Wait

#

so when I do this

leaden ice
#

you should copy the keys to a collection (as per my example) in the other thread, then pass the copy over to the other thread

mighty ivy
#

and use it there

#

it's not creating a copy? it's a reference?

leaden ice
mighty ivy
leaden ice
#

yeah

mighty ivy
#

oh darn

leaden ice
#

and the KeyCollection is like a view into the actual dictionary

#

you should just make it take a list

mighty ivy
#

oh.. uhm, well is there a way to create a list with it? Without running through all the dictionary

leaden ice
#

and pass in objectSources.Keys.ToList()

mighty ivy
#

because creating the list takes a lot of time

mighty ivy
#

argh

leaden ice
#

isn't it fine if it takes time, since this is in the other thread?

mighty ivy
#

no, no it's not

leaden ice
#

it's not fine or it's not in the other thread

#

what are you trying to do exactly?

mighty ivy
#

So, I have two lists, one has all the objects of the game and the other has another good half of the obejcts (that contain chunks and thousands of other obstacles in the procedural world). The first list is a dictionary of GameObject and NavMeshBuildSource pair. Really easy to handle because you can add and remove objects from the dictionary with their reference. The other one is a list that gets created every time a build is requested. Populating it doesn't take much time. Everything works well in a thread, and I build the navmesh manually with the async method. The problem is when the dictionary has 1) to be converted in a list and 2) merged with the other list (I'm using AddRange). I moved all the code from the main thread to another thread, that "listens" to a concurrentQueue that holds a pair of KeyCollection list and the other NavMeshSourceList to be merged with. This works well until I get that exception above, and I guess it's because the keyCollection is modified while the detatched thread was still reading the queue.

#

if you prefer I can use pastebin to paste the whole class, but it's a bit messy, I'm still trying to optimize and tidy things 😅

leaden ice
#

Why does the dictionary have to be converted in a list / merged with another list exactly?

mighty ivy
#

Because you need a single list of sources to build

leaden ice
#

and yes siunds like a threading issue - aka modifying the dict while it's being read in the other thread

mighty ivy
mighty ivy
jaunty sundial
#

Hey so i have a game object i want to rotate so that its orientation is always parallel to how the camera is looking at it so if the camera is looking at it down wards the object will tilt downwards etc. how would i go about doing this

mighty ivy
#

And manually creating the list in the main thread simply nullifies the effort to move the code that lags in the other thread

fervent furnace
#

set its transform.forward=cam.tf.foward

jaunty sundial
swift falcon
#

I have a slight issue that MeshColliders contactOffset doesn't seem to take affect during runtime if I change it?

MeshCollider meshCol = target.GetComponent<MeshCollider>();
meshCol.convex = true;
meshCol.isTrigger = true;
meshCol.contactOffset = 0.2f;```But the trigger distance doesn't change at all? Is there a function or anything I can call to set this?
naive swallow
#

Currently, I have a zooming function with an orthographic camera, where scrolling the mousewheel changes the camera's orthographic size. If I wanted to zoom in on the mouse, I'm not sure how I'd go about having it zoom on that specific point. I'm guessing there's some sort of math I can do to move the camera as I change the ortho size so that the mouse'd position remains stationary, but I'm not entirely sure how I'd go about determining that math.

jaunty sundial
fervent furnace
#

idk but if your camera will rotate and you can get its tf it should work

heady iris
#

Yes. Cinemachine moves the main camera.

#

You could also use a Copy Rotation constraint.

orchid bane
#

All our game objects are in UI. The canvas' render mode is Screen Space - Camera. Is there any way to give "depth" to the objects? So that when the character is behind an objects it's rendered behind it. I am considering giving each object a separate canvas with another Plane Distance value but perhaps there is a better way? Changing Z position in world space coordinates sounds like a bad idea. If it's unclear, the game is 2.5D

plush hedge
orchid bane
naive swallow
#

That's kind of the source of your troubles

#

Probably shouldn't do that

plush hedge
#

Ideally, you should be using SpriteRenderer and Z position for 2D with depth.

#

UI is really for UI... Like menus, inventory, etc.

fervent furnace
#

given a max size and min orthogonal size (max size: camera dont move, min size: the point at the center of screen), so you can have a equation: camera position= t* camera original position+(1-t)***point ** where t is (current size-min size)/(max size-min size)<- this is constant
point is ofc screen to world point (input.mouse position)

#

this is just a linear equation, if you want fancy movement, please modify it...

naive swallow
fervent furnace
#

yes

naive swallow
#

Okay, I'm giving it a shot

gleaming imp
#

The namespace '<global namespace>' already contains a definition for 'Timer'

static matrix
#

can I have one navmeshsurface that encompanies multiple objects (not one object with children))

gleaming imp
#

called global namespace?

naive swallow
#

global namespace is where scripts that don't specifically have a namespace defined go

woeful dagger
#

hello everybody i have a probleme with websocket how can help me?
There is already one outstanding 'SendAsync' call for this WebSocket instance. ReceiveAsync and SendAsync can be called simultaneously, but at most one outstanding operation for each of them is allowed at the same time
i want to click button and a want sendmessage (active tracking)
and in updatefixe => sendmessage (my postion)
when i put a button to active (tracking camera) => i have got this message (how i can do?)

static matrix
#

BuildNavMesh is the same as baking it correct?

rigid island
#

should be

gleaming imp
#

how would you troubleshoot this

rigid island
static matrix
#

you probably set something up wrong

#

is it possible to add new objects to a navmesh?

plush hedge
#

Branching dialogue system in Unity?

gleaming imp
static matrix
#

issue found, great job, heres a raise 💸

rigid island
#

you have to rebake

static matrix
#

yes

#

like if I instatiate a new object while running can I bake it into the navmesh

rigid island
static matrix
#

ok ill keep trying

gleaming imp
#

yeah this isn´t a amissing namespace problem, it´s something else

#

some kind of bug

rigid island
gleaming imp
#

UI package?

rigid island
#

yea

gleaming imp
#

hm

#

nope

rigid island
#

then how is it a bug lol

gleaming imp
#

i thought it´s built in

rigid island
#

it usually is there by default

#

but its a package

#

if you remove it, bye bye scripts

static matrix
#

ioleksdfjiewlkfj I feel like i'm on the cusp of solving this issue i've had for half a year

#

the CUSP

naive swallow
static matrix
#

calling an issue like this a unity bug feels like calling something witchcraft

leaden ice
thick socket
#
        if (SystemInfo.deviceType == DeviceType.Handheld)
#

this doesn't return mobile when using Unity's built in Simulator?

leaden ice
#

simulators are not emulators

thick socket
#

darn

#

thanks 🙂

gleaming imp
#

@static matrixit does feel like witch hunt tbh

static matrix
#

Bugs with your code vs bugs with your setup

gleaming imp
#

Assembly 'Assets/PlayServicesResolver/Editor/Google.JarResolver_v1.2.59.0.dll' will not be loaded due to errors:
Assembly name 'Google.JarResolver' does not match file name 'Google.JarResolver_v1.2.59.0'

this looks like... deprecated API or something?

#

I can find the .dlls in the project but not the Assembly name 'Google.JarResolver' so I could rename it

simple egret
#

The assembly name is contained in the DLL, as bytes, it's the library name

gleaming imp
#

so then I should rename the file instead to match the assembly name

fervent vapor
#

Hey, I was following a tutorial and I am curious why there is an if state about the velocity vector which is Vector3D and it's magnitude square should be greater than 0, before we fix the smoothing of the rotation.
if (velocity.sqrMagnitude > 0) { character.transform.rotation = Quaternion.Slerp(character.transform.rotation, Quaternion.LookRotation(velocity), character.rotationDampTime); }

naive swallow
leaden ice
#

it has no way of knowing which way to look when it's not moving, so it's best to just leave the previous rotation alone

fervent vapor
#

am I right?

leaden ice
#

they both will be 0 when the velocity is 0

#

essentially we're just checking for the velocity being 0

fervent vapor
#

I see, so in either case Magnitude or sqrMagnitude we can check weather velocity is zero or not

naive swallow
#

How would I get the world position a screen point would be at if the camera were at a different orthographic size? Just changing the ortho size and doing ScreenToWorldPoint didn't do it, the two values were the same so I guess it doesn't actually move the camera until the end of the frame

static matrix
#

hmmm for some reason it isn't re-baking

#

idk why

#

like it bakes once on startup but then it doesn't bake again when I call it again

naive swallow
static matrix
#

ends up doing this

#

any reason why it isn't baking in the new stuff?

#

I should probably show code lol

#
  void GenerateFromCenter()
    {
        
        for (int x = -2; x < 3; x++)
        {
            for (int z = -2; z < 3; z++)
            {
                bool Occupied = false;
                foreach (Chunk c in Chunks)
                {
                    if(c.coords.X == x+Center.X && c.coords.Z == z + Center.Z)
                    {
                        Occupied = true;
                    }
                }
                if (!Occupied)
                {
                    GenerateChunk(new Coords(x + Center.X, 0, z + Center.Z));
                }
               


            }
        }
        BuildMesh();
        //Surface.transform.position = PlayerIn.transform.position;
        


    }
    public async Task BuildMesh()
    {
        await Task.Run(Surface.BuildNavMesh);
        Surface.UpdateNavMesh(Surface.navMeshData);
    }

GenerateFromCenter is called every 1 second with invokerepeating

kindred hearth
#

this causes an infinite loop sometimes

#

why

leaden ice
static matrix
#

what should I do instead
I thought task.run would work as it has worked before

leaden ice
# kindred hearth

i can't imagine this ever NOT being an infinite loop except when the length is 0

static matrix
#

yeah while is very goofy

leaden ice
#

Shouldn't this just be if, not while?

#

while is not goofy

#

while works exactly as advertised

kindred hearth
static matrix
#

it can be goofy
its a shotgun of a loop
don't miss with it

static matrix
leaden ice
#

if will suffice

kindred hearth
#

should I put it at

static matrix
#

why is it at the start????

#

put it in update or fixedUpdate

kindred hearth
#

bc it is a collider checker

leaden ice
#

or in a coroutine

static matrix
#

what should I use instead of task.run then?

kindred hearth
#

I just need to check if its not going to spawn an enemy in a wall

leaden ice
leaden ice
mellow sigil
#

I think they're just trying to find a suitable starting location for the object

static matrix
#
public void Generate()
    {
        Rand = Random.Range(30, 31);
        WallRand = 20;

        LastChunk = ChunkForLevel[Random.Range(0, ChunkForLevel.Count)];
        Center = new Coords(0, 0, 0);
        for (int x = -2; x < 3; x++)
        {
            for (int z = -2; z < 3; z++)
            {

                GenerateChunk(new Coords(x, 0, z), true);


            }
        }
        Playerstats = GameObject.Find("Player").GetComponent<PlayerStats>();
        Playerstats.LevelStats = this;

        HasGeneratedMap = true;
        Task.Run(Surface.BuildNavMesh);
        Surface.UpdateNavMesh(Surface.navMeshData);
        InvokeRepeating("CheckDespawn", 1, 1);
        InvokeRepeating(nameof(GenerateFromCenter), 1.1f, 1.1f);
    }

this does build it correctly

mellow sigil
#

so they're right in that if you only check once you might pick another bad spot

static matrix
#

I do need the rebake to be asynchronoius bcause its expensive and I cant exactly have a freeze every second

leaden ice
#

because this is wrong code for that

kindred hearth
#

but I was also only checking for colliders once

leaden ice
#

notice you are never picking another spot again

kindred hearth
#

yup

#

I saw that

kindred hearth
#

I see that there is a problem

static matrix
#

I can't just append "async" to a function and magically have it run on the not main thread correct?

kindred hearth
#

this is an array

leaden ice
#

no you don't want update here then, you do want a loop, you just need to write the code properly

kindred hearth
#

arent they unmutable?

kindred hearth
leaden ice
kindred hearth
#

this at start?

static matrix
#

should I set up a coroutine?

wraith vector
#

On "Runtime Network Stats" what is "RTT To Server"?
Whether I send player position as float or short it shows 1.5kB/s

heady iris
#

pretty sure "RTT" means "Round Trip Time"

#

not sure why it'd be showing an amount of traffic..

#

can you show the entire window?

wraith vector
#

I am confused too.
Should not traffic get halved when using short too?

heady iris
#

oh, that's two different things

#

RTT To Server is up top

#

0.00 seconds

#

(i presume you're running the server on the same machine)

#

The lower graph is plotting bandwidth usage

static matrix
#

its wierd, I had gotten it to work async before

#

but now it isnt

lean sail
wraith vector
#

ahh

heady iris
wraith vector
#

ty for the info

mellow sigil
# kindred hearth this at start?

The first two lines are the wrong way around. And you have to put in a safety valve so that it won't get stuck if there is no available free spot

wraith vector
#

I was getting so confused lol

heady iris
#

you could absolutely do a bunch of work on another thread as long as none of it touches unity

#

At that point I'd consider using the Jobs system

kindred hearth
#

I think there will always be available space

static matrix
#

ill try looking at jobs

heady iris
mellow sigil
heady iris
#

It offers some safety guarantees

#

and combined with Burst, you can get native code performance

static matrix
#

is it relatively simple?

kindred hearth
mellow sigil
#

make it a for loop for 1000 loops for example and break when it finds a spot

heady iris
lean sail
heady iris
#

Here, let me show you some (old-ish) code of mine

static matrix
#

ok

static matrix
#

thank you

kindred hearth
#

@mellow sigil this?

wraith vector
mellow sigil
#

Now you're breaking when it doesn't find a spot

kindred hearth
#

the else

#

my bad

lean sail
wraith vector
#

I only see them when player is moving then it goes back to 0

#

this is all I am sending:

_x.Value = (short)(transform.position.x * 10);
_z.Value = (short)(transform.position.z * 10);
_yRot.Value = (short)(rotation);```
heady iris
#

send the transform

#

matrix4x4 is 16 floats, so that's 64 bytes

lean sail
heady iris
#

64 * 30 would be around 1,800

wraith vector
#

I am confused with what you mean notlikethis

lean sail
bold pawn
heady iris
#

but I just realized Verve is manually sending this anyway

heady iris
wraith vector
#

since player move in a 2d plane I do not need X and Z rotation and Y position, nor the scale

wraith vector
#

but, i was moving my character without adding a NetworkTransform added to my player object since I do not need the accuracy of it

heady iris
#

There is probably some overhead from using multiple network variables.

wind orchid
#

Hi

#

I have A, B, C, E, and F Vector3 positions (ABFE is a rectangle)

#

How can I calculate the position of the D

thick socket
#

If I have a scene with a lot of enemies that all have their own AI...how can I speed up performance?

fervent topaz
#

how can I get a script in library to recognise a script in assets folder?

thick socket
#

(I guess I should look into what Jobs are lol)

fervent topaz
#

the script just gives an error because it cant read from assets

jaunty sundial
#

hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas

knotty sun
fervent topaz
#

then what do I do?

#

I need the script in library to read the script I have in assets

steady moat
knotty sun
fervent topaz
#

then whats my alternative?

knotty sun
#

put the script into the library and read that in Assembly-CSharp

heady iris
#

specifically.

dusk apex
fervent topaz
#

I have a script in library that creates objects and I want those objects created to have a script from assets attached to them

thick socket
heady iris
fervent topaz
#

tpyeof?

thick socket
heady iris
#

typeof(SomeType) produces a Type from a type name, yes

steady moat
heady iris
#

you're asking how to dig up a treasure chest when you have no idea where it is

fervent topaz
#

typeof(ScriptName)?

heady iris
#

you could dig thousands of holes, or you could get a metal detector

heady iris
#

But yes, that's the idea.

thick socket
fervent topaz
#

is a script name a type?

heady iris
#
public class FooComponent : MonoBehaviour {

}
fervent topaz
#

if I had a script named AppleScript it would be typeof(AppleScript)?

heady iris
#

this declares a type named FooComponent

#

It's not the name of the script asset. It's the name of the actual class.

#

(very recent versions of unity allow the names to differ)

thick socket
fervent topaz
#

FooComponent fc= gameObject.AddComponent(typeof(FooComponent )) as FooComponent ;

#

?

heady iris
# thick socket

this is telling you that physics is taking up 7ms of your 9ms frame

steady moat
heady iris
fervent topaz
#

then what do I do?

steady moat
#

You can start by reducing collider and rigidbody that arent usefully

fervent topaz
#

how do I get library to know foocomponent?

heady iris
#

because, again, circular dependency

fervent topaz
#

gameObject.AddComponent(typeof(FooComponent ))?

heady iris
#

unless the library and the rest of your code are in the same assembly

thick socket
#

I mean, I've got like 1 rb on each enemy and like 3 colliders

heady iris
#

I should stop you here and ask what you mean by "library"

thick socket
#

not much I can get rid of there

#

(would jobs be something that could help here?)

fervent topaz
#

its a package script

steady moat
jaunty sundial
#

hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas

fervent topaz
#

I want to edit the package script to add an asset script to the gameobject it creates

heady iris
#

its a package script

thick socket
#

they all look like this

#

I mostly just use the rb for moving, checking speed and falling

#

maybe I should just figure out how to write my own gravity class and get rid of rb?

steady moat
steady moat
#

At least, that it is what I do most of the time.

#

Also, if you are able to use Cercle instead of Box it should be better

eternal wagon
#

I am trying to setup Unity levelplay for ads.. do I need ironsource? how to just use Unity Ads?

thick socket
steady moat
thick socket
#

why use rb at all at that point

steady moat
#

Because of collision

#

Also, you would most likely use the velocity property of the RB for your movement/gravity

thick socket
#

colliders work without rb?

steady moat
heady iris
#

they work, but you won't get collision events if neither side has a rigidbody.

#

you may also miss collisions if you're just moving colliders around without a rigidbody

#

Switching off continuous collision detection may improve performance

#

although

#

"SolveContinuous" is already at 0.00ms in there

steady moat
#

Anyway, you see how profiling is actually important. Because your issue is not your managed code and you arent losing anytime with that for no reason.

heady iris
#

indeed

thick socket
#

would disabling everything that "can't" collide help also?

steady moat
#

Also, do you have polygone collider ?

thick socket
#

had square for everything mostly

#

or 2 circles for AI detection

steady moat
thick socket
#

just like a 4pt square around the blade instead of 8pt polygon?

#

or a really big square

steady moat
thick socket
#

detecting when he hits the player with the weapon

steady moat
#

Do you need that much precision for a collision hit ?

thick socket
#

not sure if a small box collider > larger circle collider

#

probably not

steady moat
#

You could probably use a box

#

Or a capsule

primal wind
#

How can i listen to the Debug/Log output of Unity? I had a in-game console working but lost the project and forgot how i did it

thick socket
heady iris
#

Primitive colliders are much faster than polygon/mesh colliders

#

It's a lot easier to decide if two rectangles overlap than two arbitrarily complex (and concave!) polygons

primal wind
#

Okay nevermind i found it

thick socket
wicked river
#

Hey can someone please help me. I upgraded to the latest version of Unity and I was met with this wall of errors. I have tried installing tmpro

heady iris
steady moat
heady iris
#

and yes, you can also have several colliders

steady moat
thick socket
#

ah, meant on one object 😄

steady moat
#

However, that would be bad practice in my opinion

thick socket
#

swapping all the box colliders to capsule and collision Detection from continous to Discrete and now I went from like 40fps->100fps thanks 😄

#

was definately not expecting such a massive difference

jaunty sundial
#

hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas

leaden ice
#

maybe some kind of physics interaction is happening? It's hard to say without details

jaunty sundial
leaden ice
#

nor would knowing that game really help me in diagnosing your game's issue

little stratus
#

So I have quite an ironic problem lmao, basically a NullReferenceException in an if statement that checks for null.
The exception is thrown on the if statement's line. I know for certain that both "block" and "block.GetComponent<BlockHandler>()" aren't null thanks to Debug.Logging them. I know that the null thing is the "surroundings[whatIsDown]", but I'm quite baffled as to why it would throw a NullReferenceException just for accessing a null value in an array and checking if it is, indeed, null. The array is also initialized and usable so that's not it either. Any help?

private void CheckDown()
{
    foreach (Transform block in transform)
    {
        if (block.GetComponent<BlockHandler>().surroundings[whatIsDown] == null)
        {
            //do stuff
        }
    }
}
leaden ice
little stratus
#

I tried debug logging it too just before the if statement and it's never null

leaden ice
#

one of block, block.GetComponent<BlockHandler>() or block.GetComponent<BlockHandler>().surroundings is null

#

that much is a fact

#

use Debug.Log and find out which

#

(assuming you're correct about which line the error is on)

little stratus
#

the line is indeed the one with the if

leaden ice
#

block.GetComponent<BlockHandler>().surroundings[whatIsDown] being null would not cause any error here

little stratus
#

ok so

little stratus
little stratus
#

ok so apparently

#
private void CheckDown()
{
    Debug.Log("DOWN");
    foreach (Transform block in transform)
    {
        Debug.Log("1: " + block);
        Debug.Log("2: " + block.GetComponent<BlockHandler>());
        Debug.Log("3: " + block.GetComponent<BlockHandler>().surroundings);
        if (block.GetComponent<BlockHandler>().surroundings[whatIsDown] == null)
        {
            //do stuff
        }
    }
}

the 2: is printing some empty stuff

#

so apparently the block handler is the problem, however here I'm iterating through all the children in this object and all of them indeed have a block handler component attached

leaden ice
#

it will tell you which object it is, and also you will be able to click on the debug log line in the console and it will highlight it for you

little stratus
#

this put right before the problematic if?

leaden ice
#

yes

little stratus
#

OH

#

yeah I got it thanks

#

for some reason in the //do stuff section I was instantiating another object and it put it as a child of this one so it bugged

#

still kinda weird but at least I know what's happening

leaden ice
#

that'll do it

#

also kind of a side effect of how weird the Transform enumerator is

somber nacelle
#

this is a code channel. but likely the templates just have not been updated for it yet

thick socket
#

Anyone good with math 😄

loud stratus
#

Me

thick socket
#

I want to pick a random direction and go that way (like a circle)

#

iirc it has something to do with trig 😄

#

easiest way to do it is pick a direction

somber nacelle
#

Random.insideUnitCircle

loud stratus
#

It does not have to do with maths btw with vectors more specifically

#

With methods basically

somber nacelle
#

or if you want 3 dimensional direction you can use Random.onUnitSphere

thick socket
somber nacelle
#

why not? it gets a random direction

leaden ice
#

otherwise you can do:

Vector3 direction = Quaternion.Euler(0, 0, Random.Range(0f, 360f)) * Vector3.right;```
#

but it's basically the same thing

thick socket
leaden ice
#

no

#

it definitely will NOT do that

#

normalization sets the magnitude of the vector to 1

#

not the individual components

thick socket
#

oh cool thanks

#

wasn't aware of that

copper star
#
    private Vector3 CalcluateForce(Vector3 target)
    {
        float distance = Vector3.Distance(new Vector3(this.transform.position.x, handPos.position.y, this.transform.position.z), target);
        float deltaVx = distance / travelTime;
        Vector3 velocityX = deltaVx * pm.orientation.forward;

        Vector3 velocityY = Mathf.Abs(Physics.gravity.y) * (travelTime / 2) * Vector3.up;

        return velocityX + velocityY;
    }

For a simple projectile simulation where I calculate the initial required velocity for an object to reach a target in designated time travelTime using projectile motion, I use this method to get the velocity, but the issue I'm having is that the object always seems to fall short? Does anyone have any suggestions as to why?

somber nacelle
#

do you have drag on the projectile?

leaden ice
copper star
#

yes it does I just needed to make sure that the starting height was from where it launched

leaden ice
#

Why isn't it just Vector3.Distance(transform.position, target)

#

if it was launched at a specific height, wouldn't it be at that height?

copper star
leaden ice
#

Also I don't think Vector3 velocityY = Mathf.Abs(Physics.gravity.y) * (travelTime / 2) * Vector3.up; is going to be accurate

#

that's only going to work in real life

copper star
#

Oh

leaden ice
#

Unity uses a discrete timestep physics simulation

#

it's not exactly the same

copper star
#

hmm yeah that could be the case

#

I verified the output magnitudes with an online projectile motion calculator and they seemed fine

#

would there be anything in terms of force mode that could affect it ?

leaden ice
#

you probably want to think more along the lines of "how many fixed timesteps is it going to take to get there horizontally"? And then calculate the speed it needs to go to spend that many fixed timesteps in the air

leaden ice
#

or using ForceMode.VelocityChange and ensuring it starts at 0 velocity

copper star
#

Currently I use AddForce(CalculateForce(target), Forcemode.Impulse);

leaden ice
#

yeah that's only going to work if it starts at 0 and the mass is exactly 1

copper star
#

I'll change it to VelocityChange and see if it has any effect

leaden ice
#

why not just rb.velocity = CalculateForce(target);

#

and rename CalculateForce to CalculateVelocity because that's what it's really doing

copper star
#

Alright I'm going to try it, thanks

atomic sinew
#

Hey party people. In my tileset-based pixel art game the character sometimes gets stuck on tiles. I guess this is because of rounding errors. This is usually easily fixable by using composite colliders, but I do have destructible tiles. Any idea how I can ignore small differences in colliders? I would prefer something like this to say using a circle collider for the characters legs (because it then awkwardly slides down edges which doesn't fit the boxy artstyle yada yada yada). Thanks!

leaden ice
copper star
somber nacelle
heady iris
#

You could prevent sliding off ledges separately

#

maybe by using high friction

atomic sinew
#

thanks! youre right i could also change the colliders on runtime since I detect edges with raycasts anyway 🙂

pliant sun
#

How would I get the local bounds in 2020.3, Renderer doesn't provide a localBounds property in that version and I'm not sure how to calculate it

heady iris
#

I'm not sure if there's a prettier way to do it

leaden ice
heady iris
#

but you'd just need to -- yeah, that

#

You could iterate over the corners and build a new Bounds out of them

leaden ice
#

note that "local bounds" isn't really a thing

#

because once you're rotated off the world axes, they no longer really make sense

pliant sun
#

Well yeah, I just mean more bounds without rotation, without the bounds expanding based on the objects rotation

leaden ice
#

since Bounds is intended to be axis-aligned

pliant sun
#

Unless i'm asking the wrong question?

leaden ice
#

Maybe? What are you trying to do?

pliant sun
#

The bounds expands if an object is rotated, I just want the bounds without it expanding

heady iris
#

hmm, just converting the world bounds wouldn't give you that, then

#

a rotated object would give you a larger bounding box than expected, since you'd be converting those inflated bound corners into local space

leaden ice
#

What are you trying to accomplish with this

heady iris
#

but yes, what is the goal here

#

not "to get the bounds before rotation"

#

that's the Y in the XY Problem

pliant sun
#

yeah im trying to word it in a way that helps, give me a moment lol

heady iris
#

don't try to word it

#

just tell us what you are doing, straight up

#

it's fine if this is a vague and ill-defined goal

pliant sun
#

wire frame around an object, following its rotation. I don't want the bounds to expand, i want the bounds to rotate with it

heady iris
#

ah, so maybe like a "selection box"

pliant sun
#

yeah actually suppose thats the best thing to call it

heady iris
#

Is this a mesh renderer, or is it skinned?

pliant sun
#

mesh renderer

heady iris
#

I'm thinking you could just record the bounds once

#

ultra goofy strategy: in Awake, briefly zero out the transform and record the bounds

pliant sun
#

script to capture the bounds on creation then draw the stored one

heady iris
#

You could even generate a mesh based off of those bounds and then attach it

leaden ice
#

then use localMin and localMax to draw the thing later as needed

#

(or store all 8 points if you want, which can be derived from the max and min)

pliant sun
#

was gonna say why are you doing it 8 times

leaden ice
#

yeah sorry that was from an earlier idea lol

quick elbow
#

Anyone know why I'm getting this warning constantly?

Saving has no effect. Your class 'UnityEditor.XR.Simulation.XREnvironmentViewManager' is missing the FilePathAttribute. Use this attribute to specify where to save your ScriptableSingleton.
Only call Save() and use this attribute if you want your state to survive between sessions of Unity.
UnityEditor.XR.Simulation.XREnvironmentViewManager:OnDisable () (at ./Library/PackageCache/com.unity.xr.arfoundation@5.0.7/Editor/Simulation/XREnvironmentViewManager.cs:169)
leaden ice
heady iris
#

it's an error in the package

leaden ice
#

if that doesn't help might just be a bug in XR

heady iris
#

they forgor

#

😦

quick elbow
#

Yeah... I tried updating everything and no dice 😦

heady iris
#

ScriptableSingleton lets you store and load data for editor utilities

#

the FilePathAttribute is optional and lets that data persist from run to run of the editor

#

so it's not really harmful, but it's a nuisance

quick elbow
#

Yeah, I realized that. It's just a really annoying warning to see lol

somber nacelle
#

this is a code channel

rocky hazel
#

Is it in graphic right or where?

quick elbow
#

Also anyone have any thoughts on general stability of Unity 2021 vs Unity 2022?

leaden ice
rocky hazel
#

Okay thx

heady iris
#

I usually use 2023, which was blowing up in my face semi-regularly

#

actually, on second thought, I did have one crash (that wasn't my fault)

quick elbow
#

That's good to know, thanks! And yeah, I just posted over there. My b

pliant sun
#

Almost got storing the bounds to work just the rotation stuff is wonky now. Need to go look up Matrix stuff properly..

#

thanks

#

ok nvm, ruined if objects are spawned with rotation

heady iris
#

I am having a ~weird~ problem with UnityEngine.Random. If I rapidly exit and enter play mode, I get the same RNG every time. This is in 2022.3.10f1 on macOS.

I peeked at Random.state (using reflection) and, after the first play session, the value is the same every time.

I have Domain Reload and Scene Reload disabled, so it's possible for static state to be leaking from play session to play session.

The s0 field always contains 2077314801 after the first play session. The first session's value is random, as expected.

If I wait for a few seconds before playing again, the state is randomized properly.

Searching for Random.state, Random.InitState, or Random.seed gives no results.

#

after interacting with the editor for a moment and hitting play again, I get a different, but still unchanging, random state

#

actually, yeah, the state I get after waiting for a few seconds also isn't actually random

#

it's just another set of values

#

...is it seeding with the number of seconds since exiting play mode?

#

nah, that isn't it

somber nacelle
#

it shouldn't be, it's only supposed to be seeded once and that seed should survive domain reloads. at least according to the docs

heady iris
#

The number I'm getting is consistent after an editor reload

#

Oh get outta here

#

Splines package.

#

It calls Random.InitState with the InstanceID of an object.

steady moat
#

lol