#archived-code-general

1 messages · Page 269 of 1

spark vigil
#

You can, but there would be no real benefit

round violet
#

well i get an errtor

spark vigil
#

Can you show the error?

heady iris
#

How are you attempting to use CrossSceneDataHolder?

round violet
#

"<myclass> doesnt derived from monoB or SO"

heady iris
#

show us the context, not just the single error message

round violet
#

let me get a new log

spark vigil
#

That error is because of this

#

You need to remove it from the game object first

heady iris
#

i'm surprised it mentions ScriptableObject at all if that's the problem, since SOs can't be attached to a game object

spark vigil
#

It's a generic "not a unity object" error, you can get it if you have a ScriptableObject asset in your project and remove the SO inheritance from it

heady iris
#

Ah, I see

spark vigil
#

Not sure why they didn't just have two separate errors, since it'd be less confusing

round violet
#

i did a test with SO, no errors, but the code didnt work

heady iris
#

It's complaining you don't derive from one of the two valid base classes for creating your own unity object, I guess

heady iris
round violet
#

its not attached

spark vigil
#

You said at the beginning that you had it on a game object

#

And you won't get that error unless that's the case

round violet
#

deleted

#

it was a dummy GO just for this script

spark vigil
#

Are there any other errors in the log from the build?

round violet
#

console is clean

spark vigil
#

The build, not the editor

round violet
#

let me get the log of the build

#

where do i get it ?

#

its not in the docs

spark vigil
#

The player-related log locations are the ones you want to look in

#

Or you can do this

round violet
#

its a plain txt so it not easy to find an error message

spark vigil
#

ctrl+f for exception

round violet
#

none

spark vigil
#

In that case, can you add some Debug.Log calls at each part? So we can make sure it's actually running

round violet
#

in the editor it is working

spark vigil
#

So, once in Restart before it sets InstantStart, once in "elsewhere 3" before it checks the value, and another inside the if block

#

I know it's working in the editor, but the player can have subtle differences sometimes, so we need to narrow down where the issue could be by determining what is actually running

round violet
round violet
#

thats why i thought you were talking about the editor

#

found the issue

#

unrelated to CrossSceneDataHolder

#

ty Zombie and Fen for helping

spark vigil
#

What was the issue, out of curiosity?

round violet
#

for some reason, a get component is failling

round violet
round violet
spark vigil
#

I might have a hunch, can you show how you're doing that GetComponent and how you're checking it?

round violet
#

awake

spark vigil
#

I mean, the actual code, it's a very specific issue if it's what I think it is

round violet
#

it does a get tag then a get comp, maybe the player didnt spawn

#

but it always work in editor, and never in build

round violet
# spark vigil I mean, the actual code, it's a very specific issue if it's what I think it is
private void Awake()
{
    _player = GameObject.FindGameObjectWithTag("Player");
    _playerC = _player.GetComponent<PlayerController>();
    _animator = GetComponent<Animator>();
    Cursor.visible = false;
    Debug.Log("Check CrossSceneDataHolder.InstantStart :" + CrossSceneDataHolder.InstantStart);
    if (CrossSceneDataHolder.InstantStart)
    {
        CrossSceneDataHolder.InstantStart = false;
        Debug.Log("Check CrossSceneDataHolder.StartInTuto :" + CrossSceneDataHolder.StartInTuto);
        if (CrossSceneDataHolder.StartInTuto)
        {
            CrossSceneDataHolder.StartInTuto = false;
            StartTutorial();
        }
        else
        {
            StartClick();
        }
    }
    else
    {
        if (!PlayerPrefs.HasKey("NewPlayer"))
        {
            _navigationSelectables.RemoveSelectable(0);
            PlayButton.SetActive(false);
            PlayerPrefs.SetInt("NewPlayer", 1);
        }
    }
}

public void StartClick()
{
    _playerC.UpdateMenuStatus(false);
    _animator.SetBool("Fade", true);
    _statsCanvas.GetComponent<Stats>().Fade(true);
    _navigationSelectables.DisableInputs();
    _playerC.InTutoLevel = false;
}
unkempt zenith
#

Does Start trigger on Instantiate?

round violet
#

_playerC.UpdateMenuStatus(false); is failling in build

spark vigil
#

Ok yeah, I think I know what the issue is then

round violet
#

im all ears

spark vigil
#

So, in the editor, GetComponent will not return null for a missing component. It will return a new instance that represents a "fake" null, and will throw an exception when you call Unity methods on it (but your own methods will still run)

#

In the player, it will actually return null

#

The reason the editor does that is so it can throw MissingReferenceException instead of NullReferenceException, but imo the tradeoff is not worth it because it causes problems like this

round violet
#

in editor

spark vigil
#

Because it's still a real instance on the C# side

round violet
#

okay

spark vigil
#

So, anything inheriting from UnityEngine.Object (including MonoBehaviour, etc) is kinda like this:

public class Object
{
    private IntPtr nativeObject;
}

When you get a fake null, it just has an "invalid" object assigned to nativeObject, so when you try to call engine functions on it, it will throw an exception. But your own functions don't know about that, so they will run fine (unless they also call engine functions themselves)

#

It's very stupid and it's a bad design that has plagued Unity from the start

plain spire
#

this sounds interesting what's going on

spark vigil
#

tl;dr unity's fake null causes yet another person headaches

plain spire
#

I didn't know fake null was a thing

spark vigil
#

That's the fun part! It tries to hide it from you but fails to do so in cases like this

round violet
#

how should i get my player

#

prob move it to start

spark vigil
#

The issue seems to be that PlayerController isn't on the game object you get from GameObject.FindGameObjectWithTag("Player");

round violet
plain spire
spark vigil
#

Do you add PlayerController through code instead of the inspector? That'd explain it

spark vigil
tropic plinth
#

hey, is fishnet the best solution for easy multiplayer ?

round violet
#

it didnt work

round violet
#

does unity load in order the scene GOs ? or is it random

spark vigil
#

I assume the problem is that StartClick is running before Awake does

#

Is the game object with this component on it disabled?

round violet
#

like from top to bottom in Hierachy

spark vigil
#

Unity will automatically put "fake null" instances into any serialized component fields too

round violet
spark vigil
#

So it's not called by anything else outside?

round violet
#

a button

#

but the player cant click before the awake so...

spark vigil
#

But if the game object is disabled, Awake doesn't run

round violet
#

nothing is disabled

plain spire
#

(I'm just really fascinated)

spark vigil
#

Unity creates an uninitialized instance of the object, and modifies the private field that references the native object

plain spire
#

hm alright

#

I've never had this happen

#

so I will live ignorantly in bliss until it does

round violet
#

why cant I get the first item of the array ?

spark vigil
#
Debug.Log(GetComponent<Camera>().GetInstanceID());
#

This will print 0 in the editor, but it will throw an exception in a build

#

(If there is no Camera component)

spark vigil
#

GetRootGameObjects()[0], not GetRootGameObjects[0]

round violet
#

i forgot its a function

#

ty

#

by the way

#
SceneManager.LoadScene("Tuto", LoadSceneMode.Additive);
SceneManager.GetSceneByName("Tuto").GetRootGameObjects()[0].SetActive(false);

will this not cause an error ?
since LoadScene will execute at the end of the frame

spark vigil
#

It might work in the editor since scene loads seem to always be synchronous there, but yeah, that probably won't work in a build

#
var operation = SceneManager.LoadSceneAsync("Tuto", LoadSceneMode.Additive);
operation.completed += _ => SceneManager.GetSceneByName("Tuto").GetRootGameObjects()[0].SetActive(false);

(I wouldn't recommend hardcoding the index of a game object in your scene though...)

round violet
#

ty

#

im am testing stuff rn, i got a fog issue

plain spire
#

and you can't access a method with a array indexer, you have to invoke with (), then use []

honest sandal
#

Can someone help me rq with an issue?

#

unity is thinking im running multiple instances of the same project, when im not

#

ive restarted unity, my comp, and uninstalled my editor version

#

and reinstalled it

knotty sun
#

screenshot your project folder contents

stable geyser
#

Good morning all! I'm attempting to make a top-down pixel art game with intuitive tool useage. So if you're standing in front of a tree, you will use your axe if you press interact, if it's a mining node, your pickaxe, etc. What would be the best way to handle the interaction button handling to find the appropriate object, and communicating with it? So like when the player presses interact, we find the most likely object they're trying to interact with, choose the appropriate tool, start the swing animation, and midway through that animation when the tool would "connect" with the object, communicate to the object that it has been interacted with. Should I use raycasts in the direction facing? Is that the best method, or is there something more accurate?

jagged snow
#

Do you typically set the position of something in the same function where you instantiate it?
I have a function thats called from another class to instantiate an AI agent, should I pass the Vector3 into there and set it or should I return the gameobject and have the class that called it set it?

rocky jackal
#

why does this rotate my object to the nav mesh agents target and not the nav mesh agents next position on its path?

west sparrow
honest sandal
knotty sun
#

yes, you

honest sandal
#

like the folders or in the engine

knotty sun
#

it's unlikely to be in the engine if you can't open the project is it?

honest sandal
#

i can open it it just doesnt export cuz of it

knotty sun
#

that is not what you said

honest sandal
stable geyser
honest sandal
#

this is what i ment

#

like it lets me open it but i cant build the part i need

knotty sun
#

you mean build

honest sandal
#

yea im new to this

knotty sun
#

I can tell, no one in their right mind would make a project in the Downloads folder

honest sandal
#

where should i put it

knotty sun
#

Anywhere that is not a Windows special folder

#

Also your bundle has no output path specified

honest sandal
#

whops

#

didnt mean to delete that

#

it clears itself when i load i think

knotty sun
#

close the project, move it somewhere sensible then screenshot that folder

honest sandal
knotty sun
#

in a Unity folder

honest sandal
knotty sun
#

you do know how to make a folder I presume

honest sandal
#

yea but like in unity's appdata?

#

im confused

knotty sun
#

no just in the root of your drive

honest sandal
#

oh ok

#

also this is why i care about the multiple instances thing

knotty sun
#

kill the project

honest sandal
#

i did

lavish frigate
#

Hey all. I want to make an enemy respawn system for a metroidvania like game. To do this, when an enemy is killed ill spawn a "grave". Now when the player exits the current room collider, i want all these graves to trigger a respawn of the enemy. How do i get all objects tagged or on layer "grave" within a polygon collider2d?

hasty canopy
lavish frigate
#

oh yeah true i guess ill make a dead enemies list and if player enters a new room respawn it

#

always taking the harder road damn lol

#

thx

honest sandal
knotty sun
#

thought it might. lesson of this is never use Windows special folders for your own stuff

honest sandal
soft shard
# stable geyser Good morning all! I'm attempting to make a top-down pixel art game with intuitiv...

You could use a raycast from your player/camera for accuracy, or maybe a capsule cast if you want to be a bit more generous with player precision, if your nodes, trees, etc have a shared interface like maybe a IInteractable setup, then you can use that or a base class to inform it that its "been connected with", this way you can call something like a .Interact() on the object and not need to know any details about the object, if you do need to know specifics (maybe to display "collecting lumber..." or something), you can have the interface either have a function or a property that returns that info, each class can override that property/function passing its type or relevant info

soft shard
primal wind
#

Is BuildPlayerOptions.locationPathName relative or a full path

#

I'm trying to make a script to create directories to put my builds

honest sandal
#

@knotty sun it still wont build tho

knotty sun
tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

soft shard
# primal wind Is BuildPlayerOptions.locationPathName relative or a full path

By the description on the docs, im going to guess its a full path (https://docs.unity3d.com/ScriptReference/BuildPlayerOptions-locationPathName.html), though you can always log it to find out, your project would exist at Application.dataPath which gives you the path to your project, then /Assets, so you can remove the last part to get the root of your project, I typically make a "Builds" folder in my project root, sometimes organized by version: https://docs.unity3d.com/ScriptReference/Application-dataPath.html

rough sorrel
#

Hi. Does anyone know how to solve the following error:
ArgumentException: Expecting value of type 'Single' but got value '(0.00, 1.00)' of type 'Vector2'
Parameter name: value
The code is the following:

float valMag = 0;
                object obj = action.ReadValueAsObject();
                if (obj == null)
                {
                    return;
                }

                Type valueType = obj.GetType();

                if (valueType == typeof(float))
                {
                    valMag = (float)obj;
                }
                else if (valueType == typeof(Vector2))
                {
                    valMag = ((Vector2)obj).magnitude;
                }
                else if (valueType == typeof(Vector3))
                {
                    valMag = ((Vector3)obj).magnitude;
                }
honest sandal
knotty sun
honest sandal
#

wut

knotty sun
#

!code

tawny elkBOT
knotty sun
#

use the large code option

soft shard
rough sorrel
#

when I click on the error, it takes me to the second line in there, the "object obj = action.ReadValueAsObject();" one

soft shard
rough sorrel
#

I don't know. That is happening when I'm trying to use the scroll axis on the mouse wheel

heady iris
#

I wouldn't expect that to happen.

#

is there a reason you need to be able to handle all of these different types?

rough sorrel
heady iris
rough sorrel
#

Yeah previously I was using that action.ReadValue<float>(), but for the scroll wheel didn't work

heady iris
#

it's plausible that unity just hasn't recompiled

#

make sure it's done that :p

#

The error would take you to the line number from the old script

#

which would probably line up

rough sorrel
heady iris
rough sorrel
#

okay

#

yeah still the same error

#

and I made sure it recompiled haha

knotty sun
honest sandal
#

i see 1 of them

knotty sun
honest sandal
#

alr

heady iris
#

ReadValueAsObject() returned null when I called it on a Vector2 action

#

this is on an InputAction, not on a CallbackContext, mind you

#

but it didn't complain about a type mixup

rough sorrel
#

I mean it doesn't return anything when I don't move the mouse scroll wheel, the error appears when I move it😅

#

well first thing, why is the scroll wheel even a Vector2D???

heady iris
#

because you picked a Vector2 input control

#

mouse wheels can often tilt to go horizontally

rough sorrel
#

Oh I didn't know that

heady iris
#

If you want a single value, switch your input action to an Axis and then pick something like

hasty canopy
heady iris
#

<Mouse>/scroll/y

hasty canopy
#

I didn't know that either

heady iris
#

you're probably using <Mouse>/scroll

visual cove
#

Hey i'm having trouble with rotations using angularvelocity to align an object rotation with a grabber's rotation. The issues are:

When approaching the negative Z direction in world space, rotation becomes extremely jittery, and even skips completely over the negative Z direction. This issue persists with both setting the angular velocity, and simply using Transform.LookAt() to store a value, then set the rotation of the object to that value with a change in the Z rotation.

As well as, when using Transform.LookAt(), the closer the object gets to the negative Z direction, the more misaligned it becomes with rotation of the Grabber. Will send a short video as well as a code snippet from all rotational changes.

TWO HANDED GRAB
public virtual void LookAtSecondary()
    {
        //Rigidbody rb = GetComponent<Rigidbody>();
        //Adjust Angular Velocity to rotate to hand
        //rb.maxAngularVelocity = 20;
        Vector3 eulerRot = secondaryGrabbable.transform.position;
        //eulerRot *= 0.95f;
        //eulerRot *= Mathf.Deg2Rad;
        //rb.angularVelocity = eulerRot / Time.fixedDeltaTime;

        transform.LookAt(eulerRot);

        Quaternion r = transform.rotation;

        r.z = mainGrabber.transform.rotation.z;

        transform.rotation = r;
    }

ONE HANDED GRAB
public virtual void GrabbedRotation(Transform rot)
    {
        if (GetComponent<Rigidbody>())
        {
            Rigidbody rb = GetComponent<Rigidbody>();
            //Adjust Angular Velocity to rotate to hand
            rb.maxAngularVelocity = 20;
            Quaternion deltaRot = rot.rotation * Quaternion.Inverse(rb.transform.rotation);
            Vector3 eulerRot = new Vector3(Mathf.DeltaAngle(0, deltaRot.eulerAngles.x), Mathf.DeltaAngle(0, deltaRot.eulerAngles.y), 
Mathf.DeltaAngle(0, deltaRot.eulerAngles.z));
            eulerRot *= 0.95f;
            eulerRot *= Mathf.Deg2Rad;
            rb.angularVelocity = eulerRot / Time.fixedDeltaTime;
        }
    }
tawny elkBOT
rough sorrel
primal wind
#

How do you use this thing???

hasty canopy
#

It says deprecated

primal wind
#

Yeah but it doesn't say that with the default overload but i can't use it because it becomes this by itself

honest sandal
rough sorrel
heady iris
heady iris
primal wind
honest sandal
heady iris
hasty canopy
heady iris
#

[performs the sign of the cross]

#

god willing

#

I'll probably be figuring that out soon though, haha

#

You have to be able to filter that, though

#

Oh you know what -- I bet that's why you got the error even though you used ReadValueAsObject

rough sorrel
heady iris
#

It's because the input action is set to produce a float and you gave it a control that produces a Vector2

#

That makes way more sense now

rough sorrel
#

okay then I have to limit what the player can actually bind it to lol

visual cove
primal wind
#

Nice

rough sorrel
heady iris
#

huh, I'm actually not sure how that behaves

woven veldt
#

why does this not work, I get this error Error CS8377 The type 'Farmland' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'IBaker.AddComponent<T>(Entity, in T)' Assembly-CSharp

spring creek
#

But what type is Farmland?

woven veldt
#

A struct

spring creek
woven veldt
#

Inherits from IComponentData

spring creek
#

Ok, just making sure

woven veldt
spring creek
#

Might be the issue?

#

At least, I never do. Just new ComponentType( field1 = whatever)

woven veldt
#

I added the constructor to try and get rid of the error I origionally had what you said before.

leaden ice
#

As the error says everything has to be a value type

heady iris
#

If you want to strore a string in an unmanaged type, you need to use one of the fixed-length strings provided by the ECS packages

#

(i forget where exactly it comes from)

rigid island
#

I think Unity.Collections

#

if it works similar to the NGO fixed string

#

unless ecs has their own version 😛

untold shard
#

Guys, is there any way to fix this? I want my bullets to come out of the gun and after being fired to focus on the camera but not suddenly, but little by little they become centralized in the camera when fired, here is the code I use

        Vector3 direction = (crosshair.transform.forward - bulletSpawn.transform.forward).normalized;
        Rigidbody rb = bullet.GetComponent<Rigidbody>();
        if (rb != null)
        {
            rb.velocity = direction * shootForce;
        }

the result (they don't get fired) =

mellow sigil
#

(crosshair.transform.forward - bulletSpawn.transform.forward) <-- this doesn't make any sense

#

just make the bulletSpawn object point where you want the bullets to go, then it's just Vector3 direction = bulletSpawn.transform.forward;

untold shard
rigid island
#

so look at the half life 2 code

prisma birch
#

Anyone familiar with the new AI Navigation package (and its gizmos)? Recently upgraded from 2021 LTS to 2023 and I'm seeing some new weird behavior where some of my enemy agents are jittering. The cyan arrow gizmo is also flicking back and forth so thinking it might be related, but I'm not sure what these arrows are supposed to represent!

rigid island
prisma birch
prisma birch
rigid island
#

the dotted meansoff navmesh

#

Blue arrow is direction to destination point
red circle is the spot where it can reach max, since thats where navmesh ends

tawdry jasper
#

I'm making irregular "zones" that trigger ambient sound and weather effects. For the sounds I made a system where I have a counter incremented on enter, and decrement on exit, so I know if the counter is 0 I'm out of all triggers. Before I factor that logic out, is there an easier way?
For rigidbody colliders I can have multiple and they will act as a single collider on the body. Is there a way to have multiple trigger colliders act as their "csg sum"? When I attached multiple colliders to an object it doesn't work I get ontriggerexit called on individual ones.

prisma birch
rigid island
#

ur just more zoomed in and ur gizmos look bigger

prisma birch
#

No dotted line, two red lines and a transparent arrow.

rigid island
#

RedLines means they are path on the navmesh

#

dotted I told you earlier means the path is off the navmesh

#

its hard to see on mine but its there

#

same way

prisma birch
#

I understand what the dotted line is mean to represent, but I don't have a dotted line in my view, just two red (non dotted) lines

#

I suppose the thing I'm more curious about is why the agent's direction seems to be going haywire. The destination is unchanging.

rigid island
#

dotted means the path is not on the navmesh

#

also Youd have to show your code and how do you call the destination

honest sandal
#

can someone help me, unity keeps making the unitystream.unity3d file to unitystream.unity3d.tmp. anyone know why?

supple pewter
#

this is causing an error

quaint rock
# supple pewter

you are not doing much to explain, but chances are the problem is beause Destroy does not happen instantly

supple pewter
#

do i destory immediately

#

destroyimmediate didnt work

quaint rock
#

also explain what the issue is

#

what the expectation was and what is happening instead

supple pewter
#

ok so in the code i destroyed an object

#

and it is a variable

#

but when i reassign the variable in the line below it

#

it says an error

#

missing reference exception

#

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

cobalt tendon
nova shale
#

I have a tower defense game where the thing being protected is a Brain. The Brain class is not static but has some static variables like health. At the end of the game you can restart the scene, but these static variables are not reset. It appears from some research this is because their being set at the class level so i would have to manually reset them at the beginning of a scene. This is not optimal.

Is there a better solution i can look into? I'm looking for a best practice, not just a work around

cobalt tendon
#

alr ty

quaint rock
#

that way you can just destroy and recreate the object and everything is back to its starting values

nova shale
#

Have them not be static causes a lot of coupling which is not a great practice

quaint rock
#

its still coupling if they are static

nova shale
#

No?

#

There's no dependency with a static reference

tender arch
quaint rock
#

yes, your other things accessing the static vars still depend on them

nova shale
#

They exists because the class exists, they dont depend on an instance, making them not static couples them to an instance

tender arch
quaint rock
cobalt tendon
#

wait

#

hold on

quaint rock
#

only thing that resets static stuff is a full domain reload which is not something you can really do in a build

cobalt tendon
#

ok so i added the public thing but it didnt work and then i deleted it again and it compiled and it somehow worked?

#

its the exact same code as before and it worked..

tender arch
cobalt tendon
#

lmao

#

thanks tho

quaint rock
#

so you will either need logic that resets them, or put them on the instance

tender arch
#

the wonders of c#

dire crown
#

Im, for the funsies, trying to replicate the Rigidbody component, but im having trouble with the rb.addforceatposition, does anyone know how I could implement it?

#
public void AddForceAtPosition(Vector3 force, Vector3 position, ForceMode mode){
    float divider = mode == ForceMode.Acceleration || mode == ForceMode.VelocityChange ? 1 : mass;
    Vector3 linear_acc = force / divider;
    Vector3 angular_acc = Vector3.Cross(position - position, force);

    _newVelocity += linear_acc * Time.deltaTime;
    _newAngularVelocity += angular_acc * Time.deltaTime;
}

Does this look right?

drifting bobcat
#

Any idea why my AI is not moving on a NavMesh that was generated during runtime using NavMeshSurface? It's showing an error "GetRemainingDistance" can only be called on an active agent that has been placed on a NavMesh."

fervent coyote
#

Can you change Scriptobjects with code?

I tried to do that, it worked, but somehow, it reverted!

knotty sun
#

does nobody read error messages?

drifting bobcat
#

It is tho

simple egret
drifting bobcat
# drifting bobcat It is tho

When i bake the mesh normally, it works, but when i bake it with the NavMeshSurface on runtime it doesn't detect it.

fervent coyote
quaint rock
#

also good idea to isntance them in memory if you dont want players in editor messing with the data on your assets

simple egret
#

You still can modify their values at runtime, but if you want to restore the changed values when a new instance of the app starts, you need to save them somewhere (to a file, for example), and load them when the game starts

knotty sun
fervent coyote
simple egret
#

No I mean via code, at runtime. You don't have access to the Editor on builds, and the game data is not easily accessible by the user (it's packed in a few asset files)

silver basin
#

hello ! can someone help me please, when i start my game, my model go down on the "Y" with the rigidbody component enable. Do you know why ?

fervent coyote
simple egret
#

I think there's a misunderstanding on what the question means

#

Can you rephrase it with more context? What are you trying to do, globally speaking

knotty sun
silver basin
knotty sun
#

does your model also have a collider

silver basin
#

Yes, capscule collider

knotty sun
#

show the terrain inspector

fervent coyote
# simple egret Can you rephrase it with more context? What are you trying to do, globally speak...

Alright, sure

I am working on re-structuring my weapon's variables
It's basically the same variables, but in a different, easier to use format

Because while I could do update the new variables with the old variables by hand, it would be easier to use code to copy/paste the variables
When I did it, it worked and changed the scriptobject variables, then I went and deleted the old variables and updated the project to use the new variables

When I tried to test the new weapons, all the updated variables (Using code) reverted back to what it was before

silver basin
dry kayak
#

smug not to but in but I was curious what other people's variable and script naming conventions are

plain spire
quartz folio
dry kayak
#

I have read that yes

native folio
#

why is my velocity being printed as 0?

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * currentSpeed * Time.deltaTime);

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);

        Debug.Log(new Vector3(controller.velocity.x, 0, controller.velocity.z).magnitude);```
quaint rock
knotty sun
#

because you only set the y value but print that as 0

native folio
#

but im moving my controller

quaint rock
#

how are you moving it

native folio
#

top 2 lines

quartz folio
#

The last we see of you moving it is solely on y

#

And Character Controller is whack and afaik it's "velocity" is just the last move

native folio
#

huh

#

ah

#

i moved my debug statement to before velocity.y and it's displaying the magnitude fine

#

so it just the last move stuff

reef garnet
#

Hi, is there a way to programmatically create the InputActionsAsset in my project folder? I've tried with AssetDatabase but it returns these errors

UnityEngine.StackTraceUtility:ExtractStackTrace ()
Babbitt.Tools.Editor.ProjectFolderSetupWizard:InitializeInputFolder (string) (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:134)
Babbitt.Tools.Editor.ProjectFolderSetupWizard:OnWizardCreate () (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:73)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)```
#
  at (wrapper managed-to-native) UnityEngine.JsonUtility.FromJsonInternal(string,object,System.Type)
  at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) [0x0005f] in <1a33381171f2411d8ffae255a64550dd>:0 
  at UnityEngine.JsonUtility.FromJson[T] (System.String json) [0x00001] in <1a33381171f2411d8ffae255a64550dd>:0 
  at UnityEngine.InputSystem.InputActionAsset.LoadFromJson (System.String json) [0x00013] in .\Library\PackageCache\com.unity.inputsystem@1.7.0\InputSystem\Actions\InputActionAsset.cs:382 
  at UnityEngine.InputSystem.Editor.InputActionImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) [0x00074] in .\Library\PackageCache\com.unity.inputsystem@1.7.0\InputSystem\Editor\AssetImporter\InputActionImporter.cs:76 )
UnityEngine.StackTraceUtility:ExtractStackTrace ()
Babbitt.Tools.Editor.ProjectFolderSetupWizard:InitializeInputFolder (string) (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:134)
Babbitt.Tools.Editor.ProjectFolderSetupWizard:OnWizardCreate () (at Assets/Babbitts-Custom-Tools/Editor/ProjectFolderSetupWizard.cs:73)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

If it isn't possible then fine I'll work around it.
I'm making a script to generate project folders for a new project

dense estuary
#

I've figured out what the problem is with my code, but I don't know how to solve it. Currently, the slope detection in my script is added by using the IsGrounded() method to check the normal of the ground the player is on. Then it converts the normal of the ground and the normal of the player to an angle. Then it says, if the angle is greater than 0, then the player is on a slope. And then using the slope detection, it says if (IsGrounded() == true && OnSlope() == false) verticalMove = 0; Basically meaning that the only vertical movement being applied while on a slope, is gravity, causing the player to fall back down the step really quickly because the gravity is constantly being applied.

jade vault
#
void FixedUpdate()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, radius, objectsLayer);

        foreach (Collider2D collider in colliders)
        {
            // Set the objects within the radius to active
            GameObject treeObject = collider.gameObject;

            if (treeObject.CompareTag("Tree"))
            {
                SetTreeObjectState(treeObject, true);
            }
        }

        // Set all other objects to inactive
        Collider2D[] allColliders = Physics2D.OverlapCircleAll(transform.position, Mathf.Infinity, objectsLayer);

        foreach (Collider2D collider in allColliders)
        {
            if (!colliders.Contains(collider))
            {
                // Set the objects outside the radius to inactive
                GameObject treeObject = collider.gameObject;

                if (treeObject.CompareTag("Tree"))
                {
                    SetTreeObjectState(treeObject, false);
                }
            }
        }
    }```

Hi, I am trying to have objects load in certain components based on being in a radius of the player. It works, however, it is not performant. With a random map, at 500x500, there is serious slowdown with the contains line. Is there a faster method of checking if the collider is not inside the radius instead of !colliders.Contains?
#

Would a hashset be more performant?

soft shard
small vortex
#

does anyone know how to use shadergraphs?

quaint rock
jade vault
#

FindObjectsOfType is extremely laggy

small vortex
#

Im having trouble with reflection and a divide node

jade vault
#

Let me implement that!

quaint rock
#

no need to loop twice

drowsy cedar
#

I want the Order in Layer to be set to 1 every time a line is drawn. I've set it to 1 on the inspector but when it instantiates its set at 0. If anyone can help much appreciated

soft shard
# reef garnet Hi, is there a way to programmatically create the **InputActionsAsset** in my pr...

That asset usually generates code for the data inside it, and then also creates a custom type matching the name of the asset (by default), so maybe its not as straight-forward as just creating a new asset of its type, what line of code are you using to try and create the asset with AssetDatabase? And is the type your creating from one that already exists in your project or some base InputActionAsset? It likely may be easier to clone an existing file and import it to your project - if you have a folder you often keep projects in, you can use that like a "local repository" and keep an input action asset youd want to copy to multiple projects in, so you can locate it from any project (by for example, getting the root of your current project, then back-naving to your "local repo") - there are other ways you could handle imports as well such as a unitypackage, or prefab or something similar as well

dense estuary
reef garnet
soft shard
dense estuary
soft shard
quaint rock
reef garnet
#

the file extension for the inputActionAsset is .inputactions

#

I can try with asset

drowsy cedar
dense estuary
reef garnet
#

guess there is no built in way to do this,

quaint rock
#

though a workaround could be to just do a few raycasts, have one slighty infront of your target incase the first hits the corner

dense estuary
soft shard
# reef garnet `.asset` just makes it a scriptableobject

Huh, your right I guess it is .inputactions my only other suggestion might be to either work around it with a pre-made action map, or maybe peak the source code of the Input package and see if you can find the Editor script that the context menu uses to create a new action map and try to replicate that code, though it sounds like a "more trouble than its worth" approach

reef garnet
#

thanks for the suggestion though

jade vault
#

Sometimes you get so stuck in doing it the way you want you forget the alternatives

merry stream
#

can anyone give me advice on how to optimize OnTriggerEnter performance wise?

quaint rock
merry stream
#

sorry, in my game projectiles can chain to the next enemy and when a lot of enemies are stacked, Physics2d.CompileContactCallbacks is taking up most of my memory in the profiler

rain minnow
merry stream
#

!code

tawny elkBOT
merry stream
quartz folio
#

Does DirectionTowardNearestEnemy get called often 👀

rain minnow
quartz folio
#

DirectionTowardNearestEnemy is eyewateringly bad

rain minnow
#

You're using a GetComponent call in each of them that should be cached . . .

quaint rock
#

yeah see a few things that can be cached, and directionTowardsNearst enemy could be greatly improved

merry stream
#

yeah it gets called every chain lol

rain minnow
#

The DirectionTowards method creates a list each time and uses linq which will produce gc allocs . . .

quaint rock
#

also contains check on a reglar list

merry stream
#

how should I optimize it

quaint rock
#

and a sort

quartz folio
#
  1. Use the non-allocating version of OverlapCircleAll
  2. Don't use .ToList unless you absolutely need to, that allocates an entire list every time it's called.
quaint rock
#

yeah not needed in this case since its jsut a orderbyand a .first that comes after

#

though would use a HashSet for enbemiesAlreadyChainedTo

rain minnow
quaint rock
#

much faster contains check, and would do it all in 1 loop from the result of OverlapCircleAll

#

can loop skip the needed items and keep track of the distances and current nearest in 1 loop which is less costly then a full sorting of it

rain minnow
#

in OnTriggerEnter use TryGetComponent for IDamageable. you don't check if it's null before accessing and passing it to Chain, though you check it for null within that method . . .

quartz folio
#

No need to use GetComponent to get any rigidbodies or colliders when Collision2D already has them

quaint rock
#

also would make sure the collison matrix is ok, and its not doing on trigger for more things then needed

merry stream
#

thanks, also, should I not use rigidbody for projectile physics?

quaint rock
#

only thing you need get component for in this is the IDamagable

quaint rock
#

defines what layers are aloud to collide with what other layers, when it comes to the OnTriggerX and OnCollisionX stuff

merry stream
#

if nothing else is triggering the collisions does it matter that its all on?

rain minnow
quaint rock
#

other little trick is you dont need to compare distance directly to get closest

quartz folio
quaint rock
#

sqrMagitude is cheaper to calculate

quartz folio
merry stream
#

wait how would I use the nonalloc circle if it just returns int

quaint rock
#

you pass it a array it files in place

rain minnow
quaint rock
#

that way you can allocate the array once and let it fill it

quartz folio
rain minnow
#

you pass in an array with the size you expect to be hit. it will only fill up to that amount. any more hits will not be recorded . . .

merry stream
#

well how would I get that array of colliders?

#

of all the nearby enemies

quartz folio
quaint rock
#

and it fills it for you, then returns how many items it put in it

rain minnow
merry stream
#

ah i see

rain minnow
merry stream
#

didnt realize it took the array as an input

quaint rock
#

it allows you to allocate the array up front, and just keep reusing the same array and memory instead of creating it anew

rain minnow
#

initialize it at declaration or in Start or smth . . .

rigid island
#

and yeah nonalloc really is a saver, shaved off 30ms and over 1KB of garbage

quaint rock
merry stream
#

wait so what should I do inplace of the linq sorts and removes

quaint rock
#

you could get the results from the overlap circle and loop them, setup a if statement that does a continue for the ones you want to skip based on if in that collection or not

#

then keep track of the min distance in a variable, and the object you got that min distance with

#

when you loop is done you will have the one with the min distance

#

also changing enemiesAlreadyChainedTo to a HashSet will make contains checks on it much faster

#

also could use MinBy instead of OrderBy even if you wanted to use linq

#

though i would recommend just doing it all in a loop

rain minnow
#

honestly, i've only ever used the NonAlloc. typically, you'd know how many objects will hit . . .

quaint rock
#

yeah i more or less only use the non alloc versions, generally have a good idea of how much i need to check

quartz folio
#

There's no reason not to use it

#

Unless you're lazy and don't want to write that teensy bit more code

quaint rock
#

also just closer to how i would do this kinda stuff in C, where i am often holding on to memory and reusing instead of spamming the crap out of malloc and free

feral tree
#

So I am watching a tutorial on how to stylize bloom shader into comic style circles, and it gives me an error in the shader pass processer that 'source' is null value, any way to fix it?

rain minnow
#

once you write an extension method for GetClosest (object) or GetClosestPoint you can use it for everything since it's a common thing to do . . .

feral tree
#

oop

merry stream
#

it sort of working and is a lot faster but im getting a few errors of MissingReferenceException: The object of type 'BoxCollider2D' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Projectile.DirectionTowardNearestEnemy (UnityEngine.Collider2D excluding) (at Assets/_Scripts/Equipment Logic/Projectile.cs:77)
https://gdl.space/fudasapogi.cs

#

can't seem to figure it out

quartz folio
#

You are not using the result of OverlapCircleNonAlloc

#

And instead you're just iterating the whole array as if it's got values assigned to it

quaint rock
#

you need to use a regular for loop

#

and only loop as high as the returned hitcount from OverlapCircleNonAlloc

quartz folio
merry stream
#

works now, thanks

#

is everything else fine in the class?

quaint rock
#

Collider2D closestEnemy = enemiesNearby[Random.Range(0, enemiesNearby.Length)];

#

can just start it off as null too

#

but you do have the right idea with distance start it at Infinity or really any number above your radius

quartz folio
#

There is no need to check if enemy is null

merry stream
#

if I set it to null i get a bunch of errors

quaint rock
#

no need to calculate the distance twice

#

as far as vector ops go its a more expensive one

quartz folio
merry stream
#

thank you guys a ton

quaint rock
#

yeah that should be greatly faster

merry stream
#

yeah its insane now

quaint rock
#

after that in the orginal code only other parts were all the GetComponents

#

so all of those that were getting stuff on the projectile you could just do in Awake and cache on a field

merry stream
#

is it better to reference the component in the inspector or get it in Start

quaint rock
#

the colliders on collisions you already have direct access to

quaint rock
#

but very small difference compared to cleaning up that 1 function

merry stream
#

kk

quaint rock
#

so like using linq, it can be a ok time saver in code that only runs once, but i tend to avoid it for anything that could be happening per frame or multiple times a frame

merry stream
#

so just use arrays when updating per frame

quaint rock
#

yeah per frame stuff or things that happen very often good to try and avoid reallocating stuff every time

rain minnow
#

you can even have a check in Awake . . .

hoary sorrel
#

I'm trying to add knockback to my game, however with the following code, the distance of which you are knocked back is very inconsistent and unpredictable.

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject == player)
        {
            playerFlashTimerActive = true;
            if (!collisionCompleted)
            {
                playerRigidbody.velocity = Vector2.zero;
                playerDirection = (player.transform.position - transform.position).normalized;
                playerRigidbody.AddForce(playerDirection * playerKnockback, ForceMode2D.Impulse);
                collisionCompleted = true;
            }
            else
            { StartCoroutine("knockbackTimer"); }
        }
    }
    void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject == player) { collisionCompleted = false; }
    }
    IEnumerator knockbackTimer()
    {
        yield return new WaitForSeconds(knockbackDuration);
        playerRigidbody.velocity = Vector2.zero;
    }

How could I alter my code so that the knockback is a consistent distance every time?

rigid island
#

wait you're already doing that

#

nvm

hoary sorrel
#

yeah

quaint rock
#

should be farily consistient

#

though will have a extra frame or less 1 frame

#

before the reset

spring creek
#

Knockback timer can't start the same frame as the addforce

quaint rock
#

also you never cancel the timer, might get weird cases with multiple knockback timers going at once

#

if like hit 2 or 3 times quickly

spring creek
#

So velocity could be set somewhere else before the timer starts. Show the movement code

spring creek
hoary sorrel
hoary sorrel
quaint rock
#

when you start a coroutine you can cache its result to a field so you can stop it later if it did not already stop on its own

hoary sorrel
hoary sorrel
spring creek
hoary sorrel
#

velocity

spring creek
hoary sorrel
#

i have conditions so that velocity wont be affected during knockback

#

like i said, i've debugged the movement code and it does not affect anything

spring creek
hoary sorrel
#

I can attach it, it's just long and I didn't want to burden you with that.

#

Give me one minute

#
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.A))
        {
            movementJustStopped = true;
        }
        if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.D))
        {
            myRigidBody.velocity = (Vector2.up + Vector2.right).normalized;
            animator.SetBool("isWalking", true);
        }
        else if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A))
        {
            myRigidBody.velocity = (Vector2.up + Vector2.left).normalized;
            animator.SetBool("isWalking", true);
        }
        else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.D))
        {
            myRigidBody.velocity = (Vector2.down + Vector2.right).normalized;
            animator.SetBool("isWalking", true);
        }
        else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.A))
        {
            myRigidBody.velocity = (Vector2.down + Vector2.left).normalized;
        }
        else if (Input.GetKey(KeyCode.W))
        {
            myRigidBody.velocity = Vector2.up;
        }
        else if (Input.GetKey(KeyCode.S))
        {
            myRigidBody.velocity = Vector2.down;
        }
        else if (Input.GetKey(KeyCode.A))
        {
            myRigidBody.velocity = Vector2.left;
        }
        else if (Input.GetKey(KeyCode.D))
        {
            myRigidBody.velocity = Vector2.right;
        }
        else
        {
            if (movementJustStopped) { myRigidBody.velocity = Vector2.zero; movementJustStopped = false; }
        }
        myRigidBody.velocity *= movementSpeed;
#

i'm sure it can be easily refactored, but that's not my priority at this moment

rigid island
#

😮

hoary sorrel
rigid island
#

this can be a few lines by using Input.GetAxis("Horizontal") / Input.GetAxis("Vertical")

hoary sorrel
#

i know lmao theres definitely a better way to go about it

hoary sorrel
#

ima try it

spring creek
#

I don't see anything that would prevent velocity change during knockback

#

I would do a bool set true in the coroutine on the first line, then set false on the last

#

If it is true, don't set velocity

hoary sorrel
#

alright

#

actually one problem, the code for the knockback is in a preset

#

so it would be hard to access from another script

rigid island
quaint rock
#

so what is the prefab, like the object causing the knockback?

hoary sorrel
#

the prefab is an enemy sprite, and it controls the knockback

#

i could dedicate a gameobject for it though

quaint rock
#

so just put the knockback logic on a public method on the player

#

have this collision logic call it

hoary sorrel
#

alright, will do

quaint rock
#

way easier then needing movement code needing to check stuff on enemies

rigid island
#

btw are you doing like topdown?

hoary sorrel
#

yeah

rigid island
#
 void Update()
 {
     inputs.x = Input.GetAxisRaw("Horizontal") * Time.deltaTime;
     inputs.y = Input.GetAxisRaw("Vertical") * Time.deltaTime;
     inputs.Normalize();
 }
 Vector2 inputs;
 private void FixedUpdate()
 {
     var moveDir = transform.TransformDirection(inputs);
     rb.velocity = moveDir;
 }``` 
Your whole code
quaint rock
quaint rock
#

but same idea just construct it with
inputs = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

rigid island
#

ohhh

hoary sorrel
rigid island
#

yeah you're right, im used to having separation of my movement code vs my animation code

hoary sorrel
#

thats probably the smarter thing to do lmao

rigid island
#

looks cleaner too

quaint rock
#

yeah my animation logic generally just checks stuff like velocity and makes decisions based on that

#

often will drive the x and y speed into the animator to drive blend trees

hoary sorrel
rigid island
#

or Invoke something else like events, if needed like grounded states etc

hoary sorrel
#

so its not a problem

hoary sorrel
#

alright, you guys just gave me a ton of homework so i'll get back to you and tell you if this solves my initial problem, thanks!

rigid island
#

you could also mitigate it by using velocity instead, by just adding to current velocity and clamp or assign it

#

either way I'd learn how to use a coroutine for a timed event like that

hoary sorrel
#

wait in the code you provided for movement, does TransformDirection look choppy? or does it have the same effect velocity would?

rigid island
#

its choppy?

quaint rock
#

all that is doing is converting from local to worldspace

hoary sorrel
rigid island
#

Also forgot to write * moveSpeed lol

#

its prob too slow

#

rb.velocity = moveDir * moveSpeed;

hoary sorrel
#

oh wait sorry my eyes glazed over that last line

rigid island
#

if its choppy maybe something else is wrong?

hoary sorrel
#

i thought you weren't changing velocity and instead using a different method of movement

#

mb

#

i'm tired lmao

quaint rock
#

if you come back to it after a break or a sleep, it will all be clearer

rigid island
quaint rock
#

yeah chances are the transform direction is doing nothing

#

unless the parent of the player is rotated on the z

hoary sorrel
#

i'm curious, why did you put the velocity in fixedupdate rather than update?

rigid island
#

although I heard even in update they wait until physics loop anyways so 🤷‍♂️
I just know its good practice

hoary sorrel
#

kk

#

testing it

#

moment of truth

rigid island
#

sorry you probably want GetAxisRaw

#

GetAxis adds smoothing

#

idk if you want that

hoary sorrel
#

yeah i was about to say it feels a little floatier

#

thx

rigid island
#
 inputs.x = Input.GetAxisRaw("Horizontal") * Time.deltaTime ;
 inputs.y = Input.GetAxisRaw("Vertical") * Time.deltaTime;
 inputs.Normalize();```
hoary sorrel
#

right.

#

movement feels fine, I'm getting an error with the knockbackTimer though

Coroutine 'knockbackTimer' couldn't be started!
UnityEngine.MonoBehaviour:StartCoroutine (string)
slime:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/slime.cs:106)

hoary sorrel
#

(in player script)

    public IEnumerator knockbackTimer()
    {
        knockbackActive = true;
        yield return new WaitForSeconds(knockbackDuration);
        myRigidBody.velocity = Vector2.zero;
        knockbackActive = false;
    }

(in enemy script)

            if (!collisionCompleted)
            {
                playerRigidbody.velocity = Vector2.zero;
                playerDirection = (player.transform.position - transform.position);
                playerRigidbody.AddForce((playerDirection * playerKnockback).normalized, ForceMode2D.Impulse);
                damageSFX.pitch = Random.Range(1, 2) + Random.value;
                damageSFX.Play();
                logic.updateHealth(-damage);
                collisionCompleted = true;
                StartCoroutine("knockbackTimer");
            }
#

ignore all the extra stuff I forgot to filter it out

rigid island
hoary sorrel
#

oh yeah true

#

I'm really bad with couroutines, how would a reference work?

rigid island
#

like a field in the inspector

#

[SerializeField] PlayerScript playerScript
playerScript.Something

#

also you want the enemy to be knocked ?

#

not sure why its in the enemy

hoary sorrel
#

i originally had it so that the player had a normal collider and the enemy had a trigger collider

#

so to not have an extra collider i put the code with the enemy instead

rigid island
#

or dont u have a damage reciever type script , that would be best

hoary sorrel
#

i already have the player gameObject referenced in the enemy code, so its not a problem, it would just be extra work to rework it

rigid island
#

alr

hoary sorrel
#

it potentially works?

#

let me just make sure

rigid island
#

not much would change so far, you'd still need to disable the movement .velocity overriding

hoary sorrel
#

i did

rigid island
#

btw Random.Range(1, 2) this will only ever give you 1

#

oh wait its using the float version nvm

hoary sorrel
#

why wouldn't it work with int?

abstract iron
rigid island
hoary sorrel
hoary sorrel
rigid island
abstract iron
abstract iron
rigid island
#

forgot the int casted into it so ide did not error

#

yup

hoary sorrel
#

whatever, i'm happy with how it sounds so I dont need a broader range than just 1

rigid island
#

idk why i second guessed myself lol

rigid island
abstract iron
#

You can't be happy with that code.

hoary sorrel
#
damageSFX.pitch = 1 + Random.value;

happy now?

rigid island
#

saved yourself a call into the same class twice 😛

abstract iron
rigid island
#

not that much here, but over time things can add up

hoary sorrel
#

ofc yeah

hoary sorrel
rigid island
#

ofc it has no effect

hoary sorrel
#

right i added in the .normalized to try and fix the original problem, forgot to delete it

#

alright, I think its finally functional!

#

thanks to everybody who helped

spring creek
cinder raft
#

how do i add or remove a function to the IAP button through script?

public CodelessIAPButton PowerUpButton => _powerUpButton;
PowerUpButton.onPurchaseComplete.AddListener(AddPlayerSpeed);// this ist working

trim schooner
#

This is a code channel and this isn't a code question. Those usually can't be selected because they're already in the project with no changes.

vestal arch
#

Why do VectorXInts have a Clamp method but VectorXs don't?

late lion
vestal arch
#

well, that's an unsatisfying answer. aight then.

humble pumice
#

Is there a better way than GetComponent to get information from an colliding object (with OnCollisionStay2D)?

vestal arch
#

is there a clean/built-in way to go from Vector2 to Vector3 with a specified z, or do you just have to set it afterwards or manually new Vector3(v2.x, v2.y, z)?

deft timber
vestal arch
#

yeah, but i'm asking if there's a built-in way

deft timber
#

there isnt

vestal arch
#

just asking out of curiosity, not need

humble pumice
deft timber
humble pumice
#

An Int

deft timber
#

from a component?

humble pumice
#

I have a viewcone. And I want it to detect if whatever is entering it is hostile or not by getting its TeamID

deft timber
#

and what is teamID

#

a int in your class?

humble pumice
#

Yes

deft timber
#

well then you have to get a reference to that class

#

then to that int

#

so there is no other way

#

than using GetComponent

humble pumice
#

Yeah, but is there a diffrent way, than using a class?

deft timber
#

you can use TryGetComponent to avoid 2x GetComponent call

#

what exactly are you trying to achieve

#

detect who is enetering your "viewcone"?

#

there is no built-in sensor or anything like that

humble pumice
#

I want not use getcomponent every frame

deft timber
#

then cache it just once

#

you dont need to ues get component everyframe, that is a veyr bad idea

humble pumice
#

Indeed

deft timber
#

you'd need to show the code

humble pumice
#
    {
        if (!IsHost) { return; }
        if (TeamManager.CheckForHostile(teamSelector.GetTeam(), trigger.GetComponent<TeamSelector>().GetTeam().id))
        {
            fire = true;
        }
    }```
deft timber
#

im not sure why are you checking for all that

#

in OnTriggerStay

#

when you just want to detect who ENTERED the viewcone

humble pumice
#

Well, if I use enter and exit. And 2 things entered the cone. It will stop shooting if one leaves and one stays

deft timber
#

you should have a list

#

of objects that are inside the view cone

#

and add/remove them in enter/exit

#

and set fire to true

#

if there is atleast 1 in the viewcone

humble pumice
#

How do I know which is which?

deft timber
#

well you have the teamid

#

dont you

#

2 lists, one for allies, one for hostiles

#

in OnTriggerEnter

#

check if its ally or hostile

#

and add it to ally or hostile list

#

then you can check allies.Count or hostiles.Count etc

#

and in exit

#

check if its ally or hostile

#

and remove it from the list

#

as simple as that

humble pumice
#

Coulnd I just make an int instead that counts how many there are? Why do I need a list?

deft timber
#

just make whatever you want

#

list.Count is also a int

humble pumice
#

lol k

cold egret
#
  • In renderparams struct, what's the difference between the layer and rendaringLayerMask properties? One being int, the latter being uint and that's it?
late lion
# cold egret - In renderparams struct, what's the difference between the `layer` and `rendari...

renderingLayerMask is a separate mask that masks based on Renderer.renderingLayerMask. Instead of culling based on GameObject layers, you can additionally cull based on Renderer.renderingLayerMask. This means you effectively have 32 additional layers you can use for rendering. Another nice thing about these layers is that each Renderer stores a mask instead of a layer index, so each Renderer can have multiple layers.

cold egret
#
  • I see. So layer is mandatory and renderingLayerMask is optional?
late lion
orchid abyss
#

i disabled sword -> player collision in the matrix but the sword still wont collide with the wall

knotty sun
orchid abyss
#

wat

knotty sun
#

what I said, read your code

worldly quarry
#

How to fix this specifiq lighting issue? I tried enabling Stich Seams but with no luck.

orchid abyss
worldly quarry
knotty sun
#

what has that to do with your code?

worldly quarry
orchid abyss
#

the 7th layer is the wall so...

knotty sun
knotty sun
orchid abyss
#

just tell me what's wrong dumbass

steep herald
#

<@&502884371011731486>

orchid abyss
#

wtf im asking you what the problem is and you dont tell mee

knotty sun
#

really? you just got yourself blocked, good luck

orchid abyss
#

huuh

rapid stump
#

😳

vagrant blade
orchid abyss
#

i posted it cause i wanted help and hes not helping..

vagrant blade
#

Don't whine please

orchid abyss
#

idk what i have to read and hes not telling me

vagrant blade
#

Nobody has to tell you anything, really. You're not owed anything here.

orchid abyss
#

how is saying read your code helpful

quaint rock
#

no one here is paid to help people, its generally just people doing it on their free time

orchid abyss
#

what is there to read

rapid stump
orchid abyss
#

when there isn't

quaint rock
#

there is

orchid abyss
#

then what

quaint rock
#

assuming you dont want the first and last case executing when its layer 6

orchid abyss
#

there noting wrong with the layers cause even the else doesn't get called

quaint rock
#

then check to make sure the collision matrix actually allows this things to collide in the first place

#

and also put a log at the start of the function to find out if its calling when you expect it too

worldly quarry
quaint rock
#

also is your collider a trigger collider

#

does it have a rigidbody

worldly quarry
#

Do not put a rigidbody on a wall?! Why whould he 😛

#

A collider is enough

quaint rock
#

talking about the character

worldly quarry
#

OOooooh

quaint rock
#

would need both a rigidbody and a collider marked as a trigger

worldly quarry
#

Yes!

lunar python
worldly quarry
leaden ice
#

Also yes your code is faulty with regard to the if/else logic

worldly quarry
#

You can also take a look at OnTriggerEnter instead of OnCollisionEnter. Make your collider a trigger and use OnTriggerEnter

orchid abyss
leaden ice
#

Show what components are on the objects

#

It seems like you're just kind of guessing right now

orchid abyss
steep herald
#

@orchid abyss This is what? It's disabled

orchid abyss
#

it gets enabled with animation event

steep herald
#

Is there a RB on the sword?

leaden ice
orchid abyss
leaden ice
#

Then the callbacks will not run

steep herald
#

then collision is forwarded to the next RB in the parent hierarchy

orchid abyss
#

oh really

leaden ice
#

A Rigidbody is required

quaint rock
#

its one of the first lines in the docs for the trigger messages

orchid abyss
#

now the sword appears in the hand for a second then disappears

static matrix
#

how can I get rid of these weird ghost tiles? (The Dirt and the Metal Block)
I can't click on them

humble pumice
#

Are Triggers or Raycast better performance wise? (for detecting enemies)

tardy crypt
#

correction: adding stuff is like hunting for the right place to add one line of code and then realizing that it's actually going to be much more than one line of code, oops...

wicked scroll
humble pumice
#

Hm. Prop makes sense. Tho I would like to know eighter way. Because I have a lot of stuff walking around

crimson trellis
#

Can someone give me a example of how to convert reflection.MethodInfo to unityevent, I just couldn't get it to work thanks in advance

reef garnet
#

I'm working on a project folder setup wizard and I like to use InputSystem so I have an inputsystem asset in the package that I can copy to my assets folder using AssetDatabase but cannot delete the original files so that they do not conflict with eachother, I have tried the MoveAsset function and it didn't work, what do I do to move/delete files in the packages folder

AssetDatabase.DeleteAsset("Packages/com.5babbittgames.babbitts-custom-tools/Runtime/Input/GameInput.inputactions");```
reef garnet
# reef garnet I'm working on a project folder setup wizard and I like to use InputSystem so I ...

So if you somehow encounter this same problem, a workaround I just found is simply renaming the destination asset name

AssetDatabase.CopyAsset("Packages/com.5babbittgames.babbitts-custom-tools/Runtime/Input/GameInput.inputactions", path + "/NEWGameInput.inputactions");

For example setting the inputactions asset to NEWGameInput.inputactions this will not get rid of the one in the original package folder but you can just use the new name in any references to the input asset, though this may still lead to headaches of missing references for the initial project

I still hope there is a way to just cut and paste from the packages folder to the assets folder with script

orchid abyss
#

😆

prisma birch
#

Anyone know how to make grouped/categorized enums for long sets of enums? Used to be able to do something like this using [InspectorName()] but doesn't appear to be working after upgrading to 2023.

{
    [InspectorName("Category A/A1")]
    A1,
    [InspectorName("Category A/A2")]
    A2,
    [InspectorName("Category B/B1")]
    B1,
    [InspectorName("Category B/B2")]
    B2,
}```
random oak
#

Anyone be able to tell me which one is the accurate one?
why do they go out of sync after a while ?

 private void Start() 
    {
        StartCoroutine(TimerRoutine());
        Application.targetFrameRate = 7;
    }
    private void Update() 
    {
        totalSecondsII += Time.deltaTime;
    }

    private IEnumerator TimerRoutine()
    {
        while(true)
        {
            yield return new WaitForSecondsRealtime(1);
            totalSeconds++;
        }
    }```
heady iris
#

the coroutine resumes on the next frame after waiting for 1 escond

#

it doesn't instantly execute the moment 1 second passes

naive swallow
random oak
heady iris
#

it's the way I'd do it

#

note that the two techniques are measuring different things

#

WaitForSecondsRealtime ignores the timescale

random oak
#

Yeah that's good for me, I'm working on a simulator game, wanted a somewhat accurate timer

#

I will use Update then !
thanks @heady iris & @naive swallow

primal wind
#

Is there a function to check for equality on all components of a vector?

icy cedar
#

Could someone help me with an error I just started with unity and haven’t seen it before it’s “TextureImporterInspector.OnlnspectorGUI must call ApplyRevertGUI to avoid unexpected behaviour. UnityEditor.TextureImporterInspector:OnDisable()” I don’t understand what that means yet lol

primal wind
#

Yeah i can manually check each component but just wanted to know if there was a built in function for that

spring creek
naive swallow
#

aVector == anotherVector

primal wind
#

x, y and z

spring creek
#

Vector1 == Vector2

primal wind
#

i wanna know if x == y == z

naive swallow
primal wind
#

Oh okay

#

thanks

spring creek
#

That is not what it sounded like you were asking haha

Can I ask why you want that? Grid system?

naive swallow
#

Well, you could do some math, like (someVector / someVector.x) == Vector3.one but that's probably worse

heady iris
#

Does it persist after restarting the editor?

icy cedar
#

Umm I’m not sure

primal wind
#

It had something to do with the Uniform Scale option

#

I think i wanted to convert one into the other

#

if possible

native idol
#

Hi. I have a problem with the interactive parts on my sail ship model.
My ship is fully fitted with primitive and convex colliders. It also has cannons, they are all set up with their own animations and Cannon Controller Script.

I want the player to be able to walk around on deck, and when he looks at a cannon, he should be able to call the FireCannon() Function in it's Cannon Controller.

So i wrote a script that projects a Raycast from the camera. At first it didn't work. The RaycastHit only found the colliders the cannons are made of. When i added a box collider as a trigger around the whole cannon and put it on the parent object, it worked! The Raycast found the trigger collider, identified it as cannon by it's tag, was able to find the Cannon Controller Script and call FireCannon().

Then i added a Rigidbody to the whole ship (the reason i crafted that convex collider setup in the first place). And now the Raycast can't find the Trigger Boxes anymore. All it finds is the big compound collider of the ship.

I think i maybe have the complete wrong approach to this problem. Can somebody help me?

ocean nova
#

or you could change the ships layer to a built in unity one called "Ignore Raycast"

heady iris
#

Sounds like you just need to grab the collider

#
if (!hit.collider.TryGetComponent(out CannonController controller))
  return;

controller.FireCannon();
#

this uses TryGetComponent to look for a CannonController

#

it bails out if it fails to find one

dawn nebula
#

Collider I imagine no since we needed to get that to do the collision, but rigidbody?

heady iris
#

I dunno. I guess we could consult the C# reference

#

public Collider collider { get { return Object.FindObjectFromInstanceID(m_Collider) as Collider; } }

it sure does something!

#

yeah, these are all properties

heady iris
#

A lot of Unity classes and structs either call native code or need to be accessible from native code

#

So they can get funky

dawn nebula
#

Well it's tossing an int as an ID in there, so it's probably some dictionary lookup?

heady iris
#

Note that none of this should really matter to you

dawn nebula
#

Uh akshully 🤓

leaden yew
#

Hi! Does anyone know how to get all scores from a bucket leaderbord in js unity cloud?

#

I use const getScoresResult = await leaderboardsApi.getLeaderboardScores(projectId, "LDBBucket"); and the result: "detail": "Score submission required to view the scores of this leaderboard",

native idol
#

@ocean nova Thank you. I tried it out just now. It worked so far as my Debug is now only finding the cannons. But as soon as the Rigidbody is on the ship it still only finds the the ship's compund collider, and can't find the trigger box on the cannons.

@heady iris Yes, i thought it would be as simple as grabbing the collider. But all it grabs is the compound collider that is generated by the ship's Rigidbody. The cannons are also part of the ship's hierarchy, so i think the Trigger Boxes are merged into the compound collider. And putting them on a different layer doesn't prevent it.

dusky pelican
#

Hello, my android build doesnt call OnApplicationQuit when i close app, but if i change it to OnApplicationFocus, its calling but now it wont work in editor now. What should i do?

civic igloo
#

I'm trying to set up an fps multiplayer game, and i have the strangest bug here where on trigger stay or enter simply doesnt get called unless it hits a player (you can see at the bottom a Debug,Log for when the rocket initially spawns and hits the player, but nothing is printed when it hits the wall for example)

heady iris
#

what do you get if you log hit.collider ?

heady iris
#

The individual colliders continue to exist

native idol
# heady iris what do you get if you log `hit.collider` ?

So, all of my ship, even the cannons, are all childs of the "Sailship" Object, which actually has no Collider on it. But "Sailship"'s childs do have colliders.
My hit.collider is now picking up all the childs with their colliders, like "railing_col" and "cannon_wheel_col.

But as soon as i put a rigidbody component on the "Sailship" Object, the same Raycast only can find the "Sailship" Collider. I still can look at the wheels of the cannon, but it only knows this collider as "Sailship" Collider. So in my understanding the Rigidbody merged all of the colliders of the childs into one big one.

And my problem is, one of the colliders on the cannon was a trigger which i used for the Raycast to find the cannon object. And now, with the Rigidbody on the "Sailship", even this Trigger Box can't be identified. It's all "Sailship" Collider.

I'm searching for a way to prevent the Trigger Box to get merged or another approach to make my cannon useable when looking at it.

heady iris
#

I do not observe this behavior.

#

Cube has a trigger collider on it. Rigidbody Test has a (kinematic) rigidbody on it.

#

A raycast finds the Cube collider, the Rigidbody Test transform, and the Rigidbody Test rigidbody

#

Show me your raycasting code.

native idol
#

`public class Interact : MonoBehaviour
{
public Transform other;

LayerMask mask;
void Start()
{
    mask = LayerMask.GetMask("Interactive");
}

// Update is called once per frame
void FixedUpdate()
{
    Physics.Raycast(transform.position, transform.forward, out RaycastHit hit,10, mask);
    other = hit.transform;
    if (other.CompareTag("Cannon"))
    {
        other.GetComponent<CannonController>().FireCannon();
    }
}

}`

heady iris
#

You're getting hit.transform

#

I said to use hit.collider beacuse that gives you the actual collider you hit

#

Do that and it'll work fine.

leaden ice
leaden ice
#

They do different things

simple egret
#

You should also use the bool value Raycast returns, to know whether it hit anything

heady iris
#

I forget if you get a null RaycastHit back

#

or if you just get one with junk data

#

the latter would be particularly problematic

#

wait, it's a struct, innit

simple egret
#

It's a struct, so default values

quaint rock
#

RaycastHit is a struct

heady iris
#

I was thinking of Collision!

#

that's a class

quaint rock
#

assuming it would be at its defualt values

#

but easier to jsut check the bool

heady iris
#

yes, definitely

quaint rock
#

also like the way code flows with it returning a bool anyways

simple egret
#

hit.transform will most likely be null, which will throw an exception if you try to access anything on it

native idol
astral nexus
#

is it bad idea to detect pressed or interacted ui elements in a canvas by raycasting with eventsystem? I don't want to use IPointer_xxx interfaces for it (for now)

drifting bobcat
#

Can someone help me with this script? im making a fnaf styled camera controller and ive benn trying to make the camera go where the cursor is. But it's not working no matter what i do, can someone pls help? 😭


public class CameraController : MonoBehaviour
{
    public float rotationSpeed = 5f;
    public float maxVerticalAngle = 30f;
    public float maxHorizontalAngle = 60f; 
    public float smoothTime = 0.12f; 

    private float pitch = 0f;
    private float yaw = 0f;
    private Vector2 rotationVelocity;

    void Update()
    {
        yaw += Input.GetAxis("Mouse X") * rotationSpeed;
        pitch -= Input.GetAxis("Mouse Y") * rotationSpeed;
        pitch = Mathf.Clamp(pitch, -maxVerticalAngle, maxVerticalAngle);
        yaw = Mathf.Clamp(yaw, -maxHorizontalAngle, maxHorizontalAngle);
        float smoothPitch = Mathf.SmoothDampAngle(transform.eulerAngles.x, pitch, ref rotationVelocity.x, smoothTime);
        float smoothYaw = Mathf.SmoothDampAngle(transform.eulerAngles.y, yaw, ref rotationVelocity.y, smoothTime);
        transform.rotation = Quaternion.Euler(smoothPitch, smoothYaw, 0f);
    }
}```
rigid island
#

let me see how I did it

drifting bobcat
#

alright

rigid island
drifting bobcat
#

It feels like an fps camera, and i want to feel like a fnaf one, so it rotates towards the cursor position on screen

#

yk?

rigid island
#

also the original has no pitch

drifting bobcat
#

Yea im not very good at math

rigid island
drifting bobcat
#

I mean i want it to be able to look up and down

#

I just want so the camera rotates towards the cursor, like in fnaf

rigid island
drifting bobcat
#

Wym? it does

rigid island
#

it actually shifts left to right

#

the original game was 2D

#

no rotations in 2D

hexed pecan
#

How does fnaf camera work, I checked a clip and it seems that it rotates when your cursor is on the edge of the screen?

rigid island
#

you could do it in unity as a slight clamped rotation

#

but original you can tell its shifting pos

drifting bobcat
#

Yeaa something like this

#

im making a 3d game tho

rigid island
#

so do a slight Yaw turn

#

clamped

#

thats how I did it before

hexed pecan
#

You should just check if your cursor is on the left or right side of the screen and then rotate at a constant rate

rigid island
#

yup had the same thing, wish i could find the project

hexed pecan
#

And top/bottom if you want that

rigid island
#

I made "Hot Zones"

drifting bobcat
#

Ok ok ok thx i'll try to do that

rigid island
#

depending on Screen.Size

drifting bobcat
#

Did something like this, i think it looks good (also kinda like scp-079 in scp:sl lol)

rigid island
crimson plaza
#

What's the advantage of creating parallaxing backgrounds with a non-orthographic camera?

#

I was doing some searching and found that hollow knight had done theirs this way, in 3d rather than 2

quaint rock
#

perspective

#

as you move towards the side, you are seeing it from a slightly different angle

#

vs with ortho you are always seeing the backgrounds from the exact same angle

crimson plaza
#

riiiight

quaint rock
#

hollow knight also does some other trickery too, they have multiple things stacked, so you see more stuff behind the first item as it reaches the edge of the screen due to the camera perspective

#

has a mix of camera types in use for backgrounds, forgrounds and the gameplay layer

pulsar holly
quaint rock
#

waht do you mean by clone?

pulsar holly
#

A prefab

#

Basically another version of an object

quaint rock
#

a prefab asset or instantiated prefab

pulsar holly
#

I think the second one

quaint rock
#

when you call instantiate it returns the instance, you can use that to access it and call methods or modify it

pulsar holly
#

Huh?

quaint rock
#
        public PuyoScript _prefab;
        
        private void Start()
        {
            var inst = Instantiate(_prefab);
            inst.dropSet = 5;
        }
pulsar holly
#

That's javascript, not C#

somber nacelle
#

you do know that var exists in other languages besides just javascript, right? and in c# it is used for an implicitly typed local variable

quaint rock
#

also method signature is totally wrong for js

crimson plaza
#

Just to learn a bit more about cameras and parallax implementations

crimson plaza
quaint rock
#

observations and a bit of ripping thigns apart to see how it ticks

crimson plaza
#

I guess they did have a really good reason to use 3d

spring creek
spring creek
quaint rock
lean sail
crimson plaza
#

I didn't even know there wasn't really a difference between project settings for 3 and 2d till today in editor(camera)

spring creek
quaint rock
spring creek
#

Going through and just adding curly braces and whitespace only does so much when it's a minefield of redundant if statements

crimson plaza
#

But nothings stopping you from using both I'd imagine

quaint rock
#

it can me, depending on the type of game you are making the grid snapping, or tilemap help

crimson plaza
#

I've been googling but I figured why not ask people who've done it before as well