#archived-code-general

1 messages · Page 17 of 1

leaden ice
#

Lerp is something that needs to happen over the course of multiple frames. You can't do it in one frame like this

clever spade
#

Lerp interpolates between a value of 0 to 1. As 0 increases towards 1, the same reasoning happens to point a. It will increase towards point b.

river lynx
#

GetComponent<Rigidbody2D>().position.y;
this is to get position of current object that has script. how do i get position of a different game object?

#

oh iknow

#

maybe

somber nacelle
regal ore
#

not really sure where this question might go, but i'm having this issue where unity forcibly takes application focus after domain reloading (e.g. after making a script change in visual studio). i think this started happening after i upgraded to 2022.2. anyone know how to disable this behavior?

mental sparrow
#

audio.Play();
does this not work with prefabs?

#

i read something about the prefab instance getting destroyed before it can play the sound but even without destroying it it's not working for some reason

#

audio is an AudioSource

slim gate
#

Hey is it in any way possible to have an infinite tilemap for a sidescroller? Using ruletiles and adding pre-made segments or rooms to the right side but always connecting those rooms using the ruletiles rules? I cant find anything about this on google?

If yes, how would I do it? Make the pre-made segments their own tilemaps as prefabs? Another way? How do I spawn them in so the ruletiles connect to the other segments?

Any help is much appreciated!

regal ore
grim flax
#

Hey
I have error SerializationException: Type 'UnityEngine.ScriptableObject' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable., while my ScriptableObject is serializable (I guess)

leaden ice
#

What are you trying to do when you see that error?

grim flax
#

Well, I created SaveSystem and I get this error when I want to save player inventory

#

return (Dictionary<string, object>)formatter.Deserialize(stream);
I guess it is this line

#

But i am not sure

leaden ice
#

period

#

and Dictionary<string, object> is just an insane thing to use too.

grim flax
#

If be honest
I did it from tutorial cause I have not idea how it could be done
So I used to use trailer and change it on my way

leaden ice
#

find a different tutorial

grim flax
#

May you want to share some another tutorial for save system?

#

ah ok

verbal grail
#

Thx. I'll post there.

shy spire
#

Is there a way to set a variable that can be accessed by any class without the need of instantiating, like a static method? For example, setting a material to that variable that any class can simple call MaterialScript.material to get

leaden ice
#

but they're often not a good idea, you're fully responsible for their lifecycle

shy spire
#

I tried them, but they didn't work how I expected, i.e., you still have to set the variable in runtime. I was more looking to something that could be set in the inspector, like you do on classes that are on objects, but on a script itself, but that doesn't seem to exist by my trial and error.

leaden ice
#

Or just use a singleton

serene geode
#

hey how would I set an integer to a gameobjects place in the array?

shy spire
serene geode
#

So, each object in this array has an integer called "placeInArray"

#

I want to set that integer to its place in the array of a separate manager object

leaden ice
serene geode
leaden ice
#

More like Awake of the manager

serene geode
leaden ice
leaden ice
grim flax
leaden ice
serene geode
leaden ice
reef crater
#

banner shows up in unity editor, but not when i build it on my iphone

shy spire
# leaden ice ScriptableObject can serve this purpose

Doesn't seem to be what I'm looking for. I need a variable that can be set outside of runtime, like a static method that doesn't need its class to be attached to an object to function. Anything that I have to create in-scene will not work. I've settled on an static variable being set by the game controller on awake.

north frost
#

Hey Guys, I'm Currently developing a platformer with a shotgun as the main gimmick. Basically when the Player shoots the shotgun, the Player should fly backwards with wanted value.
My Problem is, that while getting the angel for the desired direction, the cursor changes the amount of the force depending where it's currently on the screen.

Since I want a constant value for the knockback, dose anyone know how I could change the Formula so that the cursor affects only the direction and not the force applied to the Rigidbody?

Code I'm currently using:

// This is all the needed Code moved Into the shoot Function (meaning some variables are declared elsewhere)
private void Shoot()
{
  mousePos = cam.ScreenToWorldPoint(_context.ReadValue<Vector2>());
  _force = new Vector2(mousePos.x - transform.position.x, mousePos.y - transform.position.y);

  rb.AddForce(-_force * knockbackForce, ForceMode2D.Impulse);
}

If I should provide more Info or examples, ask :)

south crag
north frost
#

Gimme a sec, going to test that real quick

south crag
#

At that point, _force needs renaming to something like forceDirection or the like, to reflect its intent

leaden ice
#

They are assets

tired tulip
#

how would you make a climbing system with animation rigging package in unity, more specifically with IKs

trail mist
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class Hover : MonoBehaviour
{
    public LayerMask layerMask;
    public Camera mainCam;
    public bool IsHovered = false;
    public GameObject selectedobject;

    void Update()
    {

        int NoOutline = LayerMask.NameToLayer("NoOutline");
        Ray ray = mainCam.ViewportPointToRay(Vector3.one/2f);
        if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, layerMask))
        {
            if (hit.transform.tag == "Hoverable")
            {
                hit.transform.gameObject.layer = LayerMask.NameToLayer("Outlined");
                Debug.Log("Changed layer to layer1");
                selectedobject = hit.transform.gameObject;
                IsHovered = true;
            }
            else
            {
                IsHovered = false;
            }
            if (IsHovered == false)
            {
                if(IsHovered == false && selectedobject != null)
               selectedobject.layer = NoOutline;
                selectedobject = null;
            }
            
        }

    }

}

i made this script so that when i hover objects with the tag hoverable , it will change the layer of the object , change the bool value ,and when im not hovering anymore , it will change the bool value and the selectedobject will change it's layer before making the selected object null

#

bug : when i hover on obj1 then obj2 , with both of them having the tag , the first hovered gameobject dont swap layers too
how can i detect this object change so i fix this bug ?

shy spire
leaden ice
#

they are assets

#

you have to reference them to access their data of course

shy spire
brisk reef
#

Hey, asking it here again because #💻┃code-beginner is busy, I used the Brackeys guide to set up movement using a 3rd person camera, and I wonder how I can make it, so the direction which the character is facing is always relative to the camera, and not the movement?

    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
        vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        if(direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; //Determine which way the character should face
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); //Take the targetAngle and smoothen the turning a bit
            transform.rotation = Quaternion.Euler(0f, angle, 0f); //Set the rotation to the angle
            Vector3 moveDirection = Quaternion.Euler(0f, angle, 0f) * Vector3.forward; //Make it so the way forward is relative to the camera
            controller.Move(moveDirection * speed * Time.deltaTime); //Move the character
        }

    }```
clever spade
brisk reef
clever spade
#

well now you want conflicting results

brisk reef
#

you know how a lot of 3rd person games have 2 camera types

clever spade
#

over the shoulder, fixed, and free

#

quite a few

brisk reef
#

actually

#

over the shoulder sounds like it

#

kinda like aiming

#

A good example is GTA5

clever spade
#

So you want the rotation to be independent?

brisk reef
#

while moving normally you can go in any direction

leaden ice
brisk reef
#

but while holding down on the sight, you can strafe left and right

brisk reef
#

yeah that's basically what I want to achieve

#

how can I do that?

clever spade
#

hint, Cosine Sine

gilded schooner
#

Hey

#

I want to know how to do a jump that increases in height the longer you have the jump button held down.

clever spade
gilded schooner
#

Like the Mario jump

brisk reef
brisk reef
gilded schooner
#

send me the link if you can find it.

brisk reef
#

Imagine jumping like a jetpack

#

the longer you hold it down, the more your height off the ground increases

#

In this unity tutorial we will take a look at how to make a cool 2D platformer controller !
The character will be able to jump higher the longer you hold down the jump key, move left and right and flip to face the direction in which he is moving !

-------------------------------------------------------------------------------------------------...

▶ Play video
runic cloud
#

is it possible for one internet tab with Unity to read what's going on in another tab with Unity?

leaden ice
digital whale
#

I'm trying to add sound to this flappy bird clone I made with GMTK's tutorial.I don't understand how to get the sound to work though.

somber nacelle
digital whale
#

It keeps saying "ArgumentNullException: Value cannot be null".I gave the bird game object an audio source component and I included the right mp3 to use for the audio clip.

somber nacelle
#

sounds like the audio clip isn't assigned to the audio source

digital whale
#

Are you sure?

leaden ice
#

show what sfx_wing is assigned to in your script instance

somber nacelle
#

Debug.Assert(sfx_wing.clip != null, "The clip is null", sfx_wing.gameObject);
throw this one line above the .Play() call and it will yell at you when the clip isn't null and you can even click the error to highlight the gameObject where it is null

digital whale
#

Okay,so I see now that the reference needs to be assigned.So how do i assign the clip to the reference?

leaden ice
#

you assign the audio source

digital whale
#

So how do i assign the audio source?

somber nacelle
#

drag the audio source that has the clip assigned into the slot in the inspector for this script

digital whale
#

Oh.I guess I forgot your supposed to do that.

#

Okay thank you

somber nacelle
#

so just to confirm, it was actually the sfx_wing variable that was null and not the AudioClip assigned to the AudioSource?

digital whale
#

it was the variable

somber nacelle
#

yeah i really dislike that the Play method can be called on a null object and not throw an NRE but instead throws an ArgumentNullException

devout solstice
#

How could I get the button that is clicked through a addlistener? The button is in a list and I have a for statement putting the addlistener on each button

leaden ice
#

or whatever other parameter you want to add

lilac zenith
#

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();    
    }

    public void EnableKinematic()
    {
        rb.isKinematic = true;
    }```
#

I am trying to access the rigidbody of not the gameobject that I have the script attached to but the object that I have attached the script manager to. This is turning off the isKinematic for the script manager

#

Any ideas? Let me know if more context is needed.

devout solstice
#

GameObject.FindObjectOfType<scriptmanager>().gameObject

leaden ice
#

the simplest way to get some other one is just to drag and drop it in the inspector instead of assigning it in your code.

lilac zenith
#

Yeah, I thought about that but the issue is there is an .fbx with about 60 different parts so I would have to go and do that for each. I was wanting to find a way that would scale. But if that is the best way then I can do it

lilac zenith
devout solstice
#

Thats what you said right?

leaden ice
#

I don't understand

#

is this for a ragdoll?

lilac zenith
#

No, sorry. I did a poor job explaining. I have the script attached to the script manager (GameObject1) and then am needing to access a function in the "On Release Hand" of a seperate game object (GameObject2). I am needing to turn off the kinematics for the GameObject2 but since the script is attached to Gameobject1 then it is turning the kinematics off for the script manager (gameobject1)

leaden ice
#

you're only mentioning two objects here

lilac zenith
#

I am needing to do that for all 60 parts

leaden ice
leaden ice
#

and loop over them all

snow geode
#
using UnityEngine;

public class FollowCursor: MonoBehaviour
{
void Update()
    {
        // Get the mouse position in screen space
        Vector3 mousePosition = Input.mousePosition;

        // Convert the mouse position to world space
    Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

        // Get the direction from the player to the mouse
        Vector2 direction = (worldMousePosition - transform.position).normalized;

        // Get the angle of the direction in degrees
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        // Rotate the player to face the mouse
        transform.rotation = Quaternion.Euler(0, 0, angle);
    }
}
```  When I start the game the player's rotation is set to the left, is there a way to make it start towards the cursor so the player rotation is not offset?
lilac zenith
#

Preferably I would like to just mention the specific game object that I am holding. Although I do think that would be a solution that would work

leaden ice
#

are you going to be "holding" one of the 60 parts?

lilac zenith
#

yes, there are esesntially 60 gameobject2's

leaden ice
#

have it always refer to whatever you're currently holding

#

and just do what you need through that variable.

lilac zenith
#

okay, I will give that a try. Thanks everyone.

plush grove
#

I'm writing (rewriting) a mod for a Unity game. I created a Basic UI that has a few buttons/text inputs that sit under a Canvas within the editor. I moved the Canvas into assets and created an asset bundle for the Canvas. Within the mod when I load/Instantiate the canvas I see it, and all of the elements under it. However I can not interact with anything. Attempting to find child components returns null. How would I get access to the inner buttons/inputs (During runtime only because I am not actually doing any building in Unity Editor, just using it to create the asset bundle)

#

Or am I better off sticking with IMGUI

soft shard
#

Im trying to restructure my character controller, the way it works now is I have a parent with a bunch of scripts that reference various parts of nested child objects (specifically the rigidbody, collider, various skinned meshes and specific bones from a rig hierarchy), the problem is I have different characters that have different rigs/skinned meshes, what might be a good way to have the parent (or some other system maybe?) link the references from x character prefabs? Atm im thinking I could give the parent a ScriptableObject and setup the references on each character there (then pass the SO to the parent when im spawning x character), but I feel as characters become more complex, that approach may get more unorganized, is there another way I could approach this problem, or does this sound normal?

leaden ice
shut scaffold
#

so im trying to make an interaction event on the inspector tht i can add it looks like its trying to work but it doesnt pop up

leaden ice
#

looks like the selection is filtering to Texture2Ds, but then you're checking if they're sprites?

left adder
#

Is 2D Unity Navmesh strong?
Or is it recommended to wright my own pathfinding algorithm ?

next seal
#

oh, which one is the correct one ?

rain minnow
leaden ice
#

I have no idea what you're doing

#

Looks like Sprite maybe?

next seal
#

Well I don't know in unity waht I have selected says texture type sprite 2d and ui

#

but idk what the difference between texture and sprite is

leaden ice
#

so you can't say "give me a bunch of Texture2D" and then say "if any of these things are not SPrites, throw an error"

#

of course an error will be thrown

#

why not just filter to Sprite?

next seal
#

because in line 16 it takes in textures and thats someone elses code to manually set pivots for each sprite in a spritesheet

#

and for sommmmeee reason it takes in texture

#

which i dont understand

plush grove
leaden ice
leaden ice
#

not sure what you mean by "Editor's event system"

plush grove
leaden ice
#

I know that

orchid bane
#

Is there a way to invoke an event in my coroutine if the coroutine was stopped?

soft shard
leaden ice
orchid bane
leaden ice
next seal
#

because maybe i can just change it

leaden ice
soft shard
orchid bane
leaden ice
plush grove
# leaden ice I'm assuming you're doing VRChat

I am not - its a mod for PlateUp. You got the buttons works -> I moved my Canvas and an Event System into an empty GameObject and added that gameobject as the only asset in the bundle - now everything loads and is clickable. I suspect I'll now have to loop through that parent game object to assign the proper listeners

leaden ice
next seal
#

oh well I will try around im sure that i can find it out, not like there is many options :D

#

thank you for your assistance

weak nacelle
#

Guys, I have an interesting conundrum here that I need a little help understanding

#
        Debug.Log("Incoming damage is spell:" + incomingDamageTable.spell);
        Debug.Log("Incoming damage is player:" + (incomingDamageTable.player != null));

        if (incomingDamageTable.player != null && !incomingDamageTable.heal)
        {
            if (incomingDamageTable.spell)
            {
                if (damageTable.Count == 0)
                    damageTable.Add(incomingDamageTable);
                                 Debug.Log(damageTable[0].spell);
                        }
                }
#

So how can the initial 2 debugs return true

#

while the final debug return false

modern creek
#

How do I remap .unitypackage files back to Unity? For some reason WinRAR captured that file extension, and when I open with (what appears to be) the unity exe, it tries to open unity hub.

weak nacelle
#

When by all means the final debug should echo the first debug since it should just be a duplicate of the first

somber nacelle
modern creek
#

I mean, it's a unity question, that's sort of nitpicky.. but.. the point is that the default app is currently unity.exe, but unity hub is opening, not unity.exe

weak nacelle
#

Does adding an entry to a list change its values somehow?

weak nacelle
#

In this case it must be though as there is no other way for this behaviour to occur?

modern creek
#

Post the code, though, the problem might not be what you think

weak nacelle
#

I already posted the code directly above

modern creek
#

your indentation is making this hard to understand - you do see that, yeah? that the Debug.Log under the if statement isn't inside the if clause?

quaint rock
#

first i would clean up that code

modern creek
#

(also just FYI you generally should embed your values in strings using the interpolation operator $, it'll make it a lot easier to read)

quaint rock
#

you are also missing a brace, so the final debug will not be conditional on the if (damageTable.Count == 0) statement

modern creek
#
Debug.Log($"Incoming damage from spell is {incomingDamageTable.spell}");
weak nacelle
#

Its not supposed to be conditional on the if statement

quaint rock
#

would have tricked me with the indentation that was showing a different intent then what the code was doing

modern creek
#

You haven't really posted enough code to understand the problem, though - you asked how the first two lines could both print true but you didn't show us how you're assigning those values...

quaint rock
#

so is the 3rd debug printing?

weak nacelle
#

Yes

#

but it is the exact same value as the initial debug

#

just after being added to the list

quaint rock
#

that would be expected with the code you show

weak nacelle
#

Except its not

#

Its false when the first debug is true

quaint rock
#

you are printing the incoming spell, then adding it to a list then printing the first element of the lists spell which is the same element

weak nacelle
#

Yes

#

But it is printing false instead of true

modern creek
#
        Debug.Log($"Spell: {incomingDamageTable.spell)}";
        Debug.Log($"Player: {incomingDamageTable.player != null}");

        if (incomingDamageTable.player != null 
            && !incomingDamageTable.heal // heal? or spell?
            && incomingDamageTable.spell
            && damageTable.Count == 0) damageTable.Add(incomingDamageTable);
#

is that what you mean?

weak nacelle
#

and then after that you would type Debug.Log(damagetable[0].spell) and it would be false despite the initial debug being true

#

It doesnt retain its value and I don't get why

modern creek
#

I mean, you're adding something to a list but you're assuming that damageTable[0] is the item? if there's anything else in the list, you're looking at the wrong item. Items are added to the end of lists, not the beginning

weak nacelle
#

There is nothing else in the list if not damageTable.Count would not be equal to zero

quaint rock
#

well you still print it no matter the length

modern creek
#

but you aren't debug.logging if count = 0

quaint rock
#

you just only add if 0

weak nacelle
#

Yes but I can check in the inspector and see that there is nothing in the list

modern creek
#

you're debug.logging it all the time because your indentation is wrong

weak nacelle
#

I am supposed to debug.log it

#

all the time

quaint rock
#

would strip it down to the most simple case and test your assumptions

modern creek
#

you don't really understand.. lemme rewrite your code

#
        Debug.Log("Incoming damage is spell:" + incomingDamageTable.spell);
        Debug.Log("Incoming damage is player:" + (incomingDamageTable.player != null));

        if (incomingDamageTable.player != null && !incomingDamageTable.heal)
        {
            if (incomingDamageTable.spell)
            {
                if (damageTable.Count == 0)
                {
                    damageTable.Add(incomingDamageTable);
                }
                Debug.Log(damageTable[0].spell); // this is printed even if the damagetable.count is 0.. in fact, it's always printed! because you add to the table BEFORE printing this anyway, and might not even refer to the thing you just added

            }
        }
#

i haven't changed your code aside from fixing your indentation and adding brackets to highlight that what your code is doing - the code as i wrote it is identical to yours, but it should be obvious now why the debug.log in the block isn't doing what you expect it to be doing

weak nacelle
modern creek
#

Also just FWIW your variable names make it really hard to decipher your intent. Booleans should have "is" or "did" or "does" or "can" before them so they just read like english. Like.. isTargetAPlayer or isHealingSpell

karmic bloom
#

Not sure if this is even possible or not, is there a way for me to take this code:

    public AudioClip GetClipByName(string clipName)
    {
        foreach(var clip in _clips)
        {
            if(clip.name == clipName)
            {
                return clip.clip;
            }
        }
        return null;
    }

And not only return a clipName but also force it to play through a specific audio source?

modern creek
#

(otherwise you ought to paste enough code so we can see what .spell and .player and .heal and damageTable actually are

modern creek
karmic bloom
#

It's not at the moment, I'm just now getting started. This is a tool I'm making

#

I can put it there however

modern creek
#
        public void PlayClip(AudioClipType type)
        {
            AudioClip c = AudioDatabase.GetClip(type);
            if (c == null)
            {
                w($"No audio clip found for {type}.");
                return;
            }
            _sfxSource.PlayOneShot(c);
        }

something like this

#

and GetClip is:

#

just maps enums to audio clips, but you have the right idea

#

just get the clip, and pass it to PlayOneShot()

#

looping over your clips each and every time looking for a string comparison is probably going to be a bad idea, but you'll find that out later 🙂

karmic bloom
#

Well the reason why is because I'm doing this in the tool:

modern creek
#

Sure, that's fine

#

and the audio manager is in your scene? make sure it's got an audio source and you're good

karmic bloom
#

Yeah it's in the scene.

#

I would like to not have to hardcode the audio source either, but I'm assuming looking for the clip and the source will eventually get to be a lot?

modern creek
#

clean up your code, too, maybe:

public void PlayClip(string clipName)
{
  AudioClip clip = _clips.Find(x => clipName);
  if (clip == null) return;
  _audioSource.PlayOneShot(clip);
}
#

What do you mean by hardcode the source?

#

Just declare it and link it in the inspector

#

Or if you're making audiomanagers elsewhere in your game and don't want to forget that step, in your OnEnable() make a GetComponentInChildren<AudioSource>() and have it throw an error if it can't find one

#

(the name audiomanager to me, though, implied a singleton, so you'd only need to do that once, ever, then forget about it)

karmic bloom
modern creek
#

I'd personally use scriptable objects for something like this, but if that's foreign to you, don't worry about it too much, it's not really required

#

Then yeah, you're golden.. if you want I'll even show you the entire source code for my audio singleton

#

does music, sfx, etc, but isn't too complex

#

the only thing AudioDatabase is doing (in mine) that you'd need to do on your own is finding the clip you want to play based on a string

#

(mine uses enums but that's nbd - you can use strings)

karmic bloom
#

It's not foreign, it's kinda hard to explain what I'm doing really. I just didn't want have the player create a scriptable object for every audio clip or am I overthinking it?

modern creek
#

players don't create scriptable objects.. you do

karmic bloom
#

Well

modern creek
#

Think of a scriptable object as a uh.. data file

karmic bloom
#

I don't mean the player

#

lol

#

I mean the game dev sorry

modern creek
#

OK, so.. they don't create an SO for every audio file, they create one for "all" of them, typically

#

mine look like this:

#

the SO is sort of .. where you link the files to the enums - then anywhere in the app, you just ask the SO for the clip you want

#

That way you don't have to .. link the clips you need to every audio source through your entire app

#

But if you're using an AudioManager singleton that you plan to have everywhere in your app, and you don't have any need to have multiple listeners or audio sources, then you're fine

karmic bloom
#

Yeah. I do want multiple sources though, for the different settings.

quaint rock
karmic bloom
#

Yeah I'm trying that now

#

I just added it

weak nacelle
modern creek
#

There should only be one listener (acutally I think there can only be one listener?) - if you have settings like volume/position/etc, you change those values on that listener.

quaint rock
karmic bloom
#

SFX, UI, Game, Master, etc

modern creek
#

OK, that's fine.. what do you mean with different settings then?

quaint rock
#

really would just have multiple lists of clips, one for each source

modern creek
#

ok, so, no problem... i'd still route all of those through your audiomanager from what I understand

quaint rock
#

so when you play a clip it figures out which list its from and plays with the associated source

modern creek
#

Hmm.. maybe, but maybe not depending on if master should intercept that

karmic bloom
#

yeah I'm trying to figure it out now. I think I have to link it through the PropertyDrawer or it won't properly pick it up

#

Since I'm using a custom GUI

modern creek
#

I'd probably but the master settings on the listener but then have all of the sources play at different volumes

karmic bloom
#

That's how I have it

#

Master is at the top then all others derive from it, but can be changed individually

next crescent
#

Is it possible to create a shortcut in unity at runtime? Say, invoking a function when certain keys are pressed and held in a specific order

soft shard
# next crescent Is it possible to create a shortcut in unity at runtime? Say, invoking a functio...

If the order is important, you could probably store your keypresses in an array or stack - otherwise if you just want to know if certain keys are currently held down, you could check for them in Update, if your using the "new" input system, you could subscribe events to an action map, or check the "wasPressedThisFrame" or "IsPressed" of the "current" Keyboard, assuming this is only important for the keyboard

rain minnow
frigid anvil
swift falcon
plush grove
#

Will transform.GetComponentInChildren<T> return all of the type in all of the children or only in the first child it encounters them?

junior aurora
#

So I have a Object(A) that is moving diagonally, I have 2 child object(B & C) on A.

A is being tweened to move diagonally.
B & C are getting a RigidBody2D added to them so that they can move away from each other with physics by adding an inpulse force to them.

B gets a force at Vector2(1,1)
B gets a force at Vector2(1,-1)

However, they are not moving in different directions at all. They stay as one.
How does rigidbody2d work when it is on a child? and the parent is constantly moving through tweening?

plush grove
leaden ice
#

Why would you need a custom inspector for that?

swift falcon
nimble dome
#

Im trying to access ParticleSystem.VelocityOverTime and the parameters for orbital and offset are available but linear doesn't appear to be. Is there another way to change it or is it not accessable from script?

leaden ice
warm wren
swift falcon
#

Lets try

frigid anvil
# warm wren Cant you do something like ```if(Attacking) {bot.SetDestination(bot.transform);}...

To a certain extent you could do that, but it's a simplification of a larger pattern, the state machine. Your object is in patrol (or destination-finding, but I'll simplify it to just 'patrol') mode, until it is attacked or finds the enemy, at which point it switches out of the patrol mode into attack mode, until the enemy (or itself) is dead, at which point it probably switches back into patrol. You can special case this, and it'll work pretty straightforwardly, but if you have more states, or substates, the code gets very complicated very quickly.

In any case, if you're using Nav Agents, there are other simple ways to stop navigating, IIRC.

warm wren
#

Yeah I guess u could set it's speed to 0 or i think use NavMeshAgent.isStopped to stop navigation

frigid anvil
# warm wren Yeah I guess u could set it's speed to 0 or i think use NavMeshAgent.isStopped t...

So I use A* Pathfinding, in general, and so it has an 'AIPath' object that gets associated with the object that moves, and I set 'canSearch' to false, and it stops looking for the next step to take. I...really should explore the basic nav mesh agents again, and see what they offer, but I vaguely recall a similar operation available on it. Essentially turning off nav mesh movement for a while.

frigid anvil
swift falcon
#

@frigid anvil @warm wren Thanks

swift falcon
#

That also works

indigo drift
#

I don’t know what I’m doing
I want to be able to use different methods from this state here, so I made an action that I can change for every state
That is not working
How do I do something like this

#

I can’t assign any methods to it. Or at least i don’t know how

cosmic rain
leaden ice
indigo drift
#

I don’t know how. Since it doesn’t appear in the inspector but I don’t know how I’d do it through code

leaden ice
#

Inspector or code

indigo drift
#

Inspector preferably?

leaden ice
#

UnityEvent is what you need then

#

Not Action

indigo drift
#

When I used unity event I couldn’t find the methods either

cosmic rain
#

But it doesn't make sense if it's for runtime states though...🤔

leaden ice
cosmic rain
indigo drift
# leaden ice Find what methods

When I go to assign the methods in the inspector with a unity event, it’s just a bunch of random scripts, I can’t find anything from the state

leaden ice
#

What are you looking at

indigo drift
leaden ice
#

You need to drag an object into the slot

#

Not a script

#

A ScriptableObject or GameObject

cosmic rain
#

So in your case it needs to be an instance of TextStates

leaden ice
#

(e.g. itself)

indigo drift
#

But this is a scriptable object, you can’t put that in the scene? It needs to be a monobehavior

leaden ice
cosmic rain
#

Unity Object instances exist not only in the scenes. SO instances and components on prefab GOs are all instances too.

indigo drift
leaden ice
#

That's the script

#

Wrong thing

#

Drag in the very asset whose inspector you're looking at

indigo drift
#

Oh shit ☠️

cosmic rain
#

Script asset is not an instance of the class that is written in it. It's just an instance of a text/script asset type(not sure what type exactly).

indigo drift
#

Okay you were right it worked

#

Thas crazy

tawny jewel
#

hey, for some reason my gameobject with rigid body and a collider wont collide with my other gameobject with collider, any idea why? (specifically it does detect oncollisonenter, but it wont lie down on the collider, it passes thorugh it instead)

leaden ice
tawny jewel
#

im moving it with transform, position, should i move it with rigidbody.moveposition instead?

#

i had some problems with it

leaden ice
#

You need to move it via the Rigidbody, yes

#

MovePosition isn't really the way though no

#

you'd move it via setting velocity and/or adding forces

tawny jewel
#

yea i heard it doest work well with other bodies types than kinematic

tawny jewel
autumn cipher
leaden ice
#

rb.velocity = something;

tawny jewel
#

ah alright, ill try that, thanks

warm wren
#

I'm jk lol

tawny jewel
#

bruh lmao

#

on the other hand though i might try it you have no idea how much issues is my powerup system generating

autumn cipher
#
public static bool RayCastOnceNonAlloc(Vector3 origin, Vector3 direction, RaycastHit hit, float maxDistance, LayerMask layermask, QueryTriggerInteraction querry = QueryTriggerInteraction.UseGlobal)
    {
        RaycastHit[] temp = new RaycastHit[1]
            { hit };

        int hitCount = Physics.RaycastNonAlloc(origin, direction, temp, maxDistance, layermask, querry);
        return hitCount > 0;
    }```
would you think this is better than the regular raycast method?
#

in terms of performance and garbage generation

boreal bone
autumn cipher
#

the bool one

boreal bone
#

I think it would be the same speed

#

because the whole point of the NonAlloc method is to avoid having to generate garbage

#

but since you created a RaycastHit[] temp = new RaycastHit[1], it gets destroyed immediately after the function returns

leaden solstice
autumn cipher
#

perhaps I should use ref/out keywords for RaycastHit?

leaden solstice
#

And your code won't have the same result as regular Raycast when there is more than one hit

autumn cipher
#

also, what?

leaden solstice
leaden solstice
autumn cipher
#

and it told me to get rid of the optional parameter for performance

#

like what

autumn cipher
leaden solstice
tawny jewel
#

quick question- what did i mess up? the bullet is chilling where it was spawned

    {
        bulletRB.velocity = Vector2.right * bulletspeed;
    }```
tough aurora
#

do raycasts detect hits if the raycast is inside of an object?

tough aurora
# leaden solstice No

is there any solution? because im tryna detect whether the player is touching air or the floor

autumn cipher
leaden solstice
tough aurora
#

with a rigidbody

autumn cipher
#

but rigidbody is a physics element

#

did you mean a collider with no rigibody?

tough aurora
#

im trying to detect if the player hops off a platform

#

i've tried using colliders

#

but it doesnt really work

autumn cipher
#

if you're using a rigidbody or character controller, you don't need a raycast for ground checks

tough aurora
#

i dont use gravity

indigo drift
#

` public UnityEvent<ChatMain> changeText;

public void doSomething(ChatMain chat)
{
    Debug.Log("a");
    chat.textSpeed = 0.01f;
} ` `
#

Sorry sent early

autumn cipher
tough aurora
indigo drift
#

this line is on ChatMain itself

autumn cipher
tough aurora
#

they're currently what im using

#

but with triggers version

autumn cipher
#

your ground won't be a trigger

tough aurora
#

im not using gravity

#

i guess ill try colliding then

autumn cipher
tough aurora
#

yeah

#

but it looks like its hopping from platform to platform

autumn cipher
tough aurora
#

should i make the collider extend or just cover the 3d model?

indigo drift
karmic bloom
#

Anybody here know where there is any documentation for changing the output device? I'm trying to allow the player to change where they hear their audio (headphones, speakers, etc). I can't seem to find any documentation though

vague tundra
#

I have a field in the parent class that I want to modify/re-declare in the child class. How can I achieve this?

cosmic rain
main shuttle
cosmic rain
karmic bloom
main shuttle
karmic bloom
vague tundra
cosmic rain
#

Maybe use an interface property instead and define the field separately in each class.

vague tundra
#

Can you make virtual properties and then override those?

#

specifically enums

west lotus
#

Why do you need this ?

vague tundra
#

All class B's inherit from class A. All class A's have a field declared and assigned.
B's need that same field but with a different value.
C's also inherit from A, also needing the field, but don't need it changed.

#

My field is an enum

west lotus
#

But putting a different value isnt overriding the prop. Just set the value you need in a init method, or start or whatever

vague tundra
#

I need the field settable in the inspector

west lotus
#

That would also just work

vague tundra
west lotus
#

The value would be stored in each instance its not tied to the parent class at all

cosmic rain
#

You jest set the value in the inspector.🤷‍♂️

west lotus
#

If you have a serializable public enum in A you can set it to what ever value you want in a instance of B

vague tundra
#

Ahh, yes of course. Thank you(: Silly me

Is it good practice to create interfaces in their own file, like classes?

cosmic rain
#

Neither bad nor good.
I'd say if the interface takes some space and there's already a lot of code in the file, move it to a different file.

#

In fact I'd move them to a new file in any case.

sour trench
#

I find myself constantly being screwed over by needing icons for things which require me to more often than not create SOs or expose it somehow to the editor just to provide it. In this case I would really just like to define status effects in the code and not have to create assets for each one, but I don't know how to provide the icon then. I've been thinking about creating a global manager that have a bunch of icon properties for icons that are shared across multiple things, such as abilities and status effects for example. However, I feel like this could grow out of control quite quickly and bloat the memory usage since you'd have icons loaded in that aren't used at a particular point in time. I've also tried loading icons from the code from a specific folder using Resources.Load but I found that it's not very reliable since paths and name of icons can change without the code knowing about it.

Do you guys have any alternative suggestions for how I could approach this problem?

public class StatusEffect : ScriptableObject
{
    public string statusEffectName; // "name" is already taken by ScriptableObject
    public string description;
    public Sprite icon;

    public virtual void ApplyEffect(BaseController caster, BaseController target) {}
}

[CreateAssetMenu(fileName = "New Bleeding Status Effect", menuName = "Data/Status Effects/Bleeding")]
public class BleedingStatusEffect : StatusEffect
{
    public override void ApplyEffect(BaseController caster, BaseController target) {}
}
thin aurora
#

Every file only consists of 1 thing - class, interface, enum, whatever

#

And the name of the file respresents what that thing is.

#

The only exception I would name is a simple record type for some obscure behaviour never used again, or File type classes. But neither of those are possible in Unity as far as I know.

#

It's just way easier in terms of readability, knowing the file's purpose without having to look into it for anything extra. If you have to consider moving it because it might become bigger than what you would accept for some reason, you might as well just put it in that new file.

vague tundra
#

Awesome, thanks!(:

void basalt
#

Is there any way to access the hardware intrinsic leading zero counter inside unity?

#

All of the ones on the docs require a later runtime version

thin aurora
#

Except stuff like applying the effect can't really be done in it because it's specific scriptable behaviour

#

The thing with these type of things is scalability, and it is probably a very good idea to just create a seperate file for them should you add more behaviour to it. It's gonna be a lot better than one bloated manager

sour trench
#

@thin aurora You mean like I have already done in my example?

vague tundra
#

My UI sprites for the individual inventory slots appear nicely in the bottom right, but the same-sized UI objects in the top left appear squished, as if their 9-slicing isn't working or something. Any thoughts?

rough brook
#

so a tutorial I am following says this

#

I have written this. only i have an error over this line and they dont in the video

main shuttle
rough brook
main shuttle
rough brook
#

I cant because of the error

thin aurora
#

That's not related

thin aurora
rough brook
#

now I want to guess its because this script is under a different namespace to the other one?

vague tundra
#

@rough brook Show code inside HealthBar.cs

rough brook
#

health is in RPG.Combat . HealthBar is in RPG.UI

vague tundra
#

Oh, yes. Likely a namespacing issue then

thin aurora
#

You have it in a namespace

#

Add using RPG.ui; at the top of the other file

#

If your IDE is set up correctly you can also press ctrl + . on HealthBar and it should give you the suggestion to add it

#

If it doesn't do that you need to configure your IDE properly

rough brook
#

now I got this. not sure what it means by protection level

thin aurora
#

Put public before it

#

Accessibility modifiers is something you should look into

vague tundra
#

I hate to say it, but its likely you've followed a tutorial that may have been slightly too advanced. If you feel too lost following the tutorial, I'd recommend learning some C# basics before tackling the tutorial(:

rough brook
#

thanks for the help guys. got it working.

rough brook
main shuttle
#

#💻┃unity-talk is the catch all channel when the question doesn't belong in the specific channels. No idea about your SSD though, you can just do a hardware check.

devout solstice
#

How could i get which button was pressed from a addlistener when the button is in a list of other buttons

thin aurora
#

Not sure if you can compare the reference, but considering it's done by checking memory (I think?), you could also use a First/Single(OrDefault) on your list

devout solstice
#

I was tryna a avoid tags but aight

forest vigil
#

How do I give a father to an object through code?

main shuttle
#

Also, don't cross post

forest vigil
#

ok thanks

#

yeah parent sounds better anyway i saw somebody else call it father so i went with that

main shuttle
#

father doesn't really exist in coding, at least I have never heard of it in 20 years.

#

Its always parent -> child relations

forest vigil
#

yea same lol

rough brook
#

I dont have a problem but I do have a question. my tutor had us learning atan2 for rotation towards an object. Why did learn that if LookAt makes it so simple?

#

we *

thin aurora
vast seal
#

thx, i'll copy paste it there 👍

plush grove
#

Whenever I use InputSystem.DisableDevice(Mouse.current); the mouse pointer disappears, I can set it visible and it comes back for a period of time but will disappear again eventually. Is that expected behavior? I can still interact with elements in my UI wherever the mouse pointer is even when not visible

cosmic rain
#

It makes better code. Same as any variable, you can pass them around

#

They are also often used for events

thin aurora
#

Storing method references in a list for example

#

Events

#

Stuff that references a method without invoking it

cosmic rain
#

You can subscribe to a delegate from different places and receive events via them. This way you reverse the dependencies and don't need to invoke methods manually.

mental rover
unreal temple
#

You can use them for callbacks. For example you could have a function like this:

IEnumerator MoveCoroutine(Vector3 to, Action onComplete) {
  while (transform.position != to) {
    transform.position = Vector3.MoveTowards(
      transform.position,
      to,
      speed * Time.deltaTime
    );
    yield return null;
  }
  onComplete();
}

void MoveAndShoot(Vector3 to) {
  StartCoroutine(MoveCoroutine(to, Shoot));
}

void MoveAndSpeak(Vector3 to) {
  StartCoroutine(MoveCoroutine(to, () => Say("hello!")));
}
#

oops, i left out the invocation lol

#

fixed now

rough brook
rough brook
mental rover
unreal temple
#

Maybe they taught you atan first hoping that you'd discover LookAt on your own

rough brook
#

is what it is. I have come out the situation knowing

mental rover
#

I'm sure you can appreciate that the easiest way to do something, that obfuscates/hides the detail, isn't necessarily in line with helping you have the best understanding and coming away with the best education though

#

sometimes it makes sense if the simple thing is a building block towards the harder thing, but sometimes it can actually be the opposite and make it harder

rough brook
unreal temple
#

That velocity calculation is unreadable!

var speed = (isCrouching, isZooming) switch {
  (true, _) => crourchWalkSpeed,
  (_, true) => zoomWalkSpeed,
  _ => walkSpeed
}
var velocity = new Vector3(
  currentDir.x * speed,
  velocityY,
  currentDir.y
);
characterController.Move(transform.TransformDirection(velocity) * Time.deltaTime);
#

Longer but at least it makes sense

rough brook
#

my tutors response was that trigonometry and pythagoras are important to everyday life not just within coding

mental rover
#

perhaps - learning can be hard, some of the best things I've learnt have been from not having the slightest clue how anything works while staring at a page in complete confusion for days

unreal temple
#

what the hell are they doing every day

#

"useful for measuring things around the house"

mental rover
#

but you try things out, experiment, figure small details out, and at a certain point it can click and you have a fantastic platform of knowledge to build on

unreal temple
#

What is WS?

#

And OS for that matter

slim spruce
late lion
#

Is it not world space and object space?

unreal temple
#

these kind of names always lead to confusion

serene egret
#

hiya! i was wondering if i could get some help on writing a script? i'm trying to understand how instantiate works atm, and want to know if i could use instantiate to spawn prefabs to the right of the player.

unreal temple
#

typically a prefab

mental rover
# rough brook my tutors response was that trigonometry and pythagoras are important to everyda...

everyday may be a stretch, but one of the biggest things you learn from mathematics in general is confidence & competence in calculation and general problem solving - having a solid understanding of trigonometry and geometry in general really can help with your intuition in every day life - you wont sit down with a pencil and start calculating a hypotenuse like you would in school, but you will intuitively understand a diagonal is longer, and about how much longer, etc

serene egret
#
 private void Spawn()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Instantiate(ladderPrefab, player.transform.position, Quaternion.identity);
            Debug.Log ("E key was pressed.");
        }
            

        if (Input.GetKeyDown(KeyCode.Q))
        {
            Destroy(ladderPrefab.gameObject);
            Debug.Log ("Q key was pressed.");
        }
    }```

i've got this atm, is there anything wrong with it so far?
unreal temple
#
// format code like this
serene egret
#

mb!

unreal temple
#

What is InstantiatePrefab?

unreal temple
serene egret
#

ack

unreal temple
#

without a space

#

nice, that's it

serene egret
#

oh sweet

#

that works :O

unreal temple
#

What is InstantiatePrefab?

serene egret
#

its supposed to say instantiate sorry

#

i forgot to update it

unreal temple
#

then what is the problem?

serene egret
#

the prefab doesn't spawn whenever i press E

unreal temple
#

@serene egret if you're making mistakes like that, it sounds like your IDE isn't configured. You should set it up using the guide in #854851968446365696, then it will autocomplete the correct name.

unreal temple
#

Or you can call this function from Update

#

Where are you calling it?

late lion
#

Destroy(ladderPrefab.gameObject); is an error. This is trying to destroy the original prefab asset, not the copy you created.

bold terrace
#

How do I convert X value and Y value from a string to an Vector2INT? For instance lets say I have string and its value is "X20Y10". How do I convert it to a Vector2INT?

serene egret
# unreal temple The test for whether E is pressed should be in Update

ive put the code into update so now that its formatted like this

    private void Update()
    {
        dirX = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            jumpSFX.Play();
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }

        UpdateAnimationState();

        if (Input.GetKeyDown(KeyCode.E))
        {
            Instantiate(ladderPrefab, player.transform.position, Quaternion.identity);
            Debug.Log ("E key was pressed.");
        }
            

        if (Input.GetKeyDown(KeyCode.Q))
        {
            Destroy(ladderPrefab.gameObject);
            Debug.Log ("Q key was pressed.");
        }
    }
serene egret
#

for e.g. say the scene doesn't have the prefab, the key inputs would be responsible for spawning and deleting them

late lion
# bold terrace How do I convert X value and Y value from a string to an Vector2INT? For instanc...

If you know for certain that the string will always be in this format and you don't need to be able to handle incorrectly formatted strings, all you need to do is find the index of the 'Y' character and then you can extract the substrings for the two numbers.

The X value will always start at index 0 and go up to where the 'Y' character is. The Y value will always start after the 'Y' character and go up to the end of the string. Then you can use int.Parse on those strings.

mental rover
late lion
serene egret
#

to be honest i only want the user to be able to spawn one ladder at a time

#

whenever searching up how to code a toggle function

#

instantiate is what came up so i've been fiddling with that so far

slim spruce
bold terrace
#

Thank you, ill check it out

devout solstice
#

Oh wait i do have a unique name

#

How would I see if it was the one that was pressed though

sage kite
#

I'm making a game in VR where you are flying on a magic carpet, i want to grab the air in VR and make the carpet follow my hands rotation

#

Any idea how?

clever harbor
#

How can I generate a Mesh with multiple materials? Specific areas/quads of the mesh will have a different material

potent sleet
mental rover
devout solstice
potent sleet
# devout solstice idk how delegates work

Watch this video in context on Unity Learn:
https://learn.unity.com/tutorial/delegates

Delegates are containers for methods (functions). They can be thought of as a variable that be called like a function to invoke whichever methods are currently stored in it. In this video you will learn to make your own delegates and use them to call various ...

▶ Play video
devout solstice
#

will this teach me what i need, to do what i’m trying to do?

sage kite
potent sleet
devout solstice
#

I just need to get what buttons being pressed when the addlistener is called

mental rover
devout solstice
#

I have a inventory system, and when one of the slots is clicked i want it to drop the item

potent sleet
devout solstice
potent sleet
devout solstice
#

Alright and that video will show me what i need?

mental rover
# sage kite That's the tricky part

yes, but that's where a lot of the problems with VR come in - user interaction is different, two free controllers and headset, each with separate position and rotation, are a novel input system and figuring out how to utilise that for interesting gameplay is basically what VR development is all about

potent sleet
mental rover
#

I'd start by trying to implement something that is line with what you want, using simple gameobject tools you're familiar with, and then come back with specific questions if it's not working how you want it to

potent sleet
#

you can pass an INT, or the Button object itself

#

up to you

devout solstice
#

How do I use the delegate with my script to pass which object is pushed though

potent sleet
devout solstice
#

Ok i think i’ve got an idea

slim spruce
potent sleet
devout solstice
devout solstice
potent sleet
#

yes , Button is a type and could be passed as well

hollow stone
#

Anyone know how this can happen? 😵‍💫 And how to make sure it doesn't happen again..

leaden ice
hollow stone
# leaden ice What is "this" which you want to stop from happening

If you see the image, one image is when clicking on a prefab in inspector, and the other when opened in prefab editor. So there is information that doesn't seem to be serialized correctly. I've had this on a few of my prefabs. I've resorted to recreating the prefab and it has solved it for now.

hollow stone
leaden ice
#

The image on the right really seems like it's not the prefab itself but an instance of the prefab 🤔

#

Mostly due to this

#

oh wait nvm

#

I see

#

Got a little confused with the naming.
Is the field in question properly serializable?
Are you using Odin Serializer or anything?

final nymph
#

Hello guys im beginner here

severe maple
#

im casting a raycast downwards in front of my player to check if there is a drop. If so, I disable the input vector2 completely (so he can't walk off ledges). However, if I am say running diagonal towards that ledge, he stops dramatically, whereas it should allow movement ALONG the ledge, just not straight off. Any idea how I would go about that? I take it involves disabling the input vector x or y that relates to the direction the ledge is in, but not sure where to start

final nymph
#

I wanna ask. How to make when the bird hits pipe then scene change to restard the gam?

uncut plank
final nymph
#

Ty bro

#

Ill try it tomorow

#

Cus now i want to sleep

potent sleet
severe maple
leaden ice
potent sleet
#

anything else will be extremely complex and not counting for edge cases

#

just my 2cents

severe maple
#

i've got a single one in front, and i guess I need at least one at the front left and right as well. So if the front detects a drop, check either side and steer the input vector towards that

leaden ice
#

literal edge cases 🤣

potent sleet
severe maple
#

any way to alter the movement vector2 I wondered? the drop will be at player.transform forward

potent sleet
#

would it really be that much to add invisible colliders, how many ledges do you really have

severe maple
#

well some levels are using terrain and drops all over the shop

steady moat
#

+1 for invisible collider

potent sleet
#

probuilder has literally a drawing tool

#

put the view Top down

#

and draw a giant thing around the egdes

severe maple
#

I have been doing invisible colliders, but what about procedural levels, would have thought there would have been a way to do it somewhere online lol

steady moat
#

Invisible Collider can be done in procedural generation

potent sleet
#

ofc its possible, anything is. it's just gonna be lot of math to deal with and consider all possible vectors which player will hit ledge from

severe maple
potent sleet
#

colliders are way easier

west prairie
#

need help

brisk reef
#

Is it just me, or is probuilder really weird to use?

potent sleet
brisk reef
#

well I just wanted to discuss it

#

not like you are forced to either ask or respond to questions here right

austere apex
#

Hi, I would need a bit of help figuring out the following (in 2d): Let's say I have a player and a tree (static object). Both have rigidbody2d and a collider (non trigger) attached to them. How can I make such that a player can pass through another player, but not through a tree. At the same time player x player collision or player x tree collision would take place.

polar marten
austere apex
#

I have tried it, but I can't "uncheck" player x player layer collision because I need them to take place

austere apex
#

Does it matter a lot? If so then suppose there is a max of 40 players in a scene. Otherwise we can just take 2 players

#

(the game is planned to be multiplayer)

polar marten
#

create a hierarchy with a separate player trigger layer and player layer

austere apex
polar marten
austere apex
#

oh I see how this can work. Will try it out. Thanks!

polar marten
#

it's okay to have multiple rigidbodies

#

i wouldn't overthink this

polar marten
austere apex
polar marten
#

you can explore corgi engine 2.5d for ✅ multiplayer ✅collide and slide physics

#

if you want your movement to be traditional platformer movement

#

you will not be able to use rigidbody physics for it

#

does that make sense?

sleek bough
#

Hello, Just want to ask why my BoxCast also detect the object behind of the other object with same layer? I only want to detect on whose in front or above

austere apex
leaden ice
austere apex
#

it's just topdown

#

In brief, moving a circle shaped player in x, y and rotating that circle in z

polar marten
#

which also has multiplayer

#

topdown movement has many fewer traditions

#

but i'm not sure you want to be futsing about with this stuff if it's already all made in an asset

austere apex
polar marten
#

if it's topdown

#

you should be working in the xz plane, not the xy plane

#

i think you should look at this moremountains top down engine asset

#

really depends what your goals are

sleek bough
safe ore
#

can someone explain to me why the interactUI isn't being turned on?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpenInteractAbleUI : Interactable
{
    [SerializeField] private GameObject interactUI;
    [SerializeField] private bool isTutorial;
    [SerializeField] private TutorialCreator tutorialCreator;
    //this is the base interaction for this object
    protected override void Interact()
    {
        interactUI.SetActive(true);
        Debug.Log(gameObject.name + " Trying to open");
        if (isTutorial)
        {
            if (tutorialCreator.seeChallenges == false)
            {
                tutorialCreator.seeChallenges = true;
                tutorialCreator.CheckTutorials();
            }
        }
    }
}
austere apex
paper rivet
#

Does the information saved with PlayerPrefs persist between updates of an android app?
If yes I have a problem: I have changed the format of the data structure with which this information is saved.
Any suggestions for how to handle this breaking change?

leaden ice
polar marten
paper rivet
polar marten
sleek bough
polar marten
leaden ice
#

those cards are splayed out in a way where the top of the bottom card is exposed for example

#

your boxcast could just be hitting that

safe ore
sleek bough
#

how to share a code again? like the shortcut?

sleek bough
# leaden ice you'd have to show _where_ the raycasts are originating etc.
private void Update()
    {
        if (isDragging)
        {
            RaycastHit hit;

            bool isHit = Physics.BoxCast(transform.position, scaleCard / 2, -transform.up, out hit, transform.rotation, m_MaxDistance, Layer);

            if (isHit)
            {
                Debug.LogWarning(hit.transform.name);
                OnTopOfCard = true;
                Target = hit.transform.GetComponentInParent<Card>().Tail;
            }
            else
            {
                OnTopOfCard = false;
                Target = null;
            }
        }
    }
leaden ice
#

Window -> Analysis -> Physics Debugger

ember lance
#
// Assume item is correctly built
Item item = new WoodItem();

if(item == null) {
  // Case is returning true even though item should not be null
}```
#

This is basically my issue

#

This happens when I derive my Main ITEM(abstract) class from MonoBehavior.

#

WoodItem is dehrived from Item

leaden ice
warm shadow
#

So I have an issue, this code is suppose to only run once, with the oneTime bool, but it still runs every frame and it spits out an NullReference Exception. Can anyone see what it is I'm missing?
Here is the code:

if (scene.name != "StartScene" && oneTime == false)
        {
            slider = null;

            slider = GameObject.FindGameObjectWithTag("Slider").GetComponent<Slider>(); //NullReferenceException here
            slider.value = startVolume;

            oneTime = true;
        }
leaden ice
#

you need to fix the exception

warm shadow
#

yes, but how?

leaden ice
#

and fix it

#

in your case either GameObject.FindGameObjectWithTag("Slider") is returning null OR the returned object doesn't have a SLider component on it so GetComponent<Slider> returns null

#

DO you actually have an:

  • active object
  • with the tag "Slider"
  • with a Slider component on it?
    in the scene?
#

At least one of those three things is missing

warm shadow
#

The gameobject is not active when you load the scene, and the NRE disappears when you activate it

#

Does that have anything to do with it?

leaden ice
#

yes

#

that would be the first thing I mentioned

#

- active object

#

FindGameObjectWithTag only finds active objects

warm shadow
#

ah sorry, i see, but how do i do it with inactive objects?

ember lance
vocal merlin
#

FindObjectsOfTypeAll works on inactive GameObjects

leaden ice
leaden ice
#

Can you not just directly reference it?

ember lance
leaden ice
ember lance
serene egret
#

im getting this error message,
'Health' does not contain a definition for 'fillAmount' and no accessible extension method 'fillAmount' accepting a first argument of type 'Health' could be found (are you missing a using directive or an assembly reference?)

and the code i have is,

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

public class HealthBar : MonoBehaviour
{
    [SerializeField] private Health playerHealth;
    [SerializeField] private Health totalHealthBar;
    [SerializeField] private Health currentHealthBar;

    private void Start()
    {
        currentHealthBar.fillAmount = playerHealth.currentHealth / 10;
    }

    private void Update()
    {
        currentHealthBar.fillAmount = playerHealth.currentHealth / 10;
    }
}

i've been trying to find the problem for a while now, but no luck. can anyone see where i've gone wrong?

leaden ice
#

My guess is you actually meant to use Image instead of Health for those fields, no?

serene egret
#

should i?

leaden ice
#

you should use Image instead of Health

#

make sense?

serene egret
leaden ice
#

So why are you trying to use such a thing?

#

You can't use things that don't exist

#
    [SerializeField] private Health playerHealth;
    [SerializeField] private Health totalHealthBar;
    [SerializeField] private Health currentHealthBar;```
#

see these?

#

You've defined them all as type Health

#

so if you do currentHealthBar.fillAmount it's looking for a fillAmount property from the Health script

#

which doesn't exist

#

hence the error

#

I'm guessing what you MEANT to do was:
[SerializeField] private Image currentHealthBar;

serene egret
#

by changing the fields Health to Image, i'm getting the same console error.

leaden ice
#

show the new code

#

show the new error

#

also make sure you saved your changes.

serene egret
#

this is embarassing

arctic panther
#

Hello! I would like to copy a unity native class and make my own variation of it. I copied the entire native script into a new one and named the class differently. It throws a bunch of errors at me. Any idea why? The most common ones are:
"must declare a body because it is not marked abstract, extern, or partial Assembly-CSharp, Assembly-CSharp.Player"
"The type or namespace name 'Orientation' could not be found (are you missing a using directive or an assembly reference?)"

The weird thing is, even if I went and fixed those erros, why do they pop up in the first place, when they work just fine in their original script?

leaden ice
#

there's a whole C++ side to them that you don't have

#

what are you trying to do?

serene egret
#

the changes ive made were

    [SerializeField] private Health playerHealth;
    [SerializeField] private Health totalHealthBar;
    [SerializeField] private Health currentHealthBar;

to

    [SerializeField] private Health playerHealth;
    [SerializeField] private Image totalHealthBar;
    [SerializeField] private Image currentHealthBar;

and the console error didn't show up anymore.
turns out it was just a problem on my behalf sorry sorry

arctic panther
# leaden ice what are you trying to do?

its a bit hard to explain so let me phrase it like this: As a unity developer I want to create an editor with a graph view that can make use of nodes. Those nodes have Ports, but the native Unity version of those ports are not working like I need them.

So my first thought was to make my own Port. inheriting from the same master class as Port, copying the script and adjusting it as I see fit.

leaden ice
arctic panther
# leaden ice What's the limitation with GraphView that you want to work around?

GraphView.Port has the following things that misfit my usecase:

  • ports are either "in" or "out". I dont need a flow in my graph view, I just need connections. (A is connected to B), without any direction
  • aesthetically: orientations. They arrange the connecting lines in a way that looks fine for a classic node flow, but Id rather have them go straight from A to B. Also I want to decide on the color of those ports.
  • the Port name is a string, I need it to be an inputfield
arctic panther
strong forge
#

Ok, so my issue is that my fields do not show up in the Inspector despite having the SerializeField attribute. (They show up in the debug but not the normal one)
This is the class in Question and it's fields (excluding methods as they are irrelevant.)

public class StateSwitchButton : NetworkButton
{
    [SerializeField] private Sprite enabledSprite, disabledSprite;
    [SerializeField] private Image enabledStateImage;
    [SerializeField] private bool defaultEnabled = false;

    [SerializeField] private UnityEvent onEnable, onDisable;

    private bool isEnabled;
}

And the class NetworkButton which it inherits from looks like this (excluding methods once again):

public abstract class NetworkButton : Button
{
    public static readonly List<NetworkButton> buttons = new List<NetworkButton>();
}

I've read somewhere that in some cases inheritance breaks the inspector, which would be a serious issue as the inheritance is required unless I pull out some workarounds.

#

This happens to every class inheriting from NetworkButton btw.

leaden ice
strong forge
leaden ice
#

so it's drawing with that custom inspector

#

which is why your fields aren't showing

strong forge
#

It worked before, it just stopped for some reason yesterday, I guess I'll have to write a custom inspector to override it, great.

strong forge
#

Thanks, I'll check it out.

stark plaza
#

how to handle screen and sprite sizes in a 2d game for mobile?

#

first time playing with mobile

warm shadow
leaden ice
warm shadow
#

I haven't used those before, but i'll look into it, thanks

hollow creek
#

hello, can anyone tell me why i am getting this error?
i had ml agents 1.0.8 package installed and i updated it to 2.0.0 and then that error appeared

foggy maple
hollow creek
#

yes

warm shadow
leaden ice
#

that whatever could be a reference to your slider
or a function that disables the slider, whatever you want.

foggy maple
# hollow creek yes

try reinstalling the package or something as that error is quite vague, just means it’s can’t find a file

warm shadow
leaden ice
#

whatever you're trying to access easily, yes

warm shadow
spare karma
#

Does someone have an idea why the editorloop keeps spiking every second on the playerloopcontroller? Some issues mentioned opened asset store window but I set the view back to default and it keeps happening

devout solstice
#

Is it causing issues?

spare karma
#

Yes, sometimes it causes a little stuttering. It’s a high end pc so there seems to be a problem somewhere

soft shard
# spare karma Does someone have an idea why the editorloop keeps spiking every second on the p...

You could try enabling "Deep Profile" and "Call Stacks", then expanding where it says "No Details" in the bottom right to show more details and run the profiler again - itll consume more RAM, but will also let you dive deeper in the raw hierarchy so you can (hopefully) see what Unity is actually trying to do during those spikes, then you can loop up those specific calls on Google, if they are documented it could give you a good indication of what it does, if not, maybe youll find a forum post about it, otherwise you may be left to investigation and trial/error (disabling certain editor windows one by one until you notice a difference)

severe maple
#

is it possible to adapt a minimap render texture camera to make it look something like this? I can understand how to do the icons easily, but I guess it would be a lot of work for walls? I was wondering if its possible to only render specific textures on layers, eg the floor textures and block everything else out, so the minimap will resemble the level layout

leaden ice
elfin wedge
#

I'm having a hard time creating an Asset Bundle. Whenever I attempt to create the asset bundle, I get an error are you missing an assembly reference? My prefab uses scripts that reference a package (https://github.com/Unity-Technologies/com.unity.webrtc), but I'm unsure on how to include the namespace from that package.

leaden ice
#

I get an error are you missing an assembly reference?
If this is a compile error you should share the full compile error and the code that causes it.

elfin wedge
#

Yes, so I have got that package working, but when I try to make my prefab into an assetbundle I get an error

#

If I build to exe or android app, everything is fine

#

I want to use my prefab as an asset bundle in another project

elfin wedge
leaden ice
#

the full error message

elfin wedge
# leaden ice the _full_ error message

D:\Github\DesktopVisionUnityPackage\Runtime\Scripts\DVConnection.cs(2,13): error CS0234: The type or namespace name 'WebRTC' does not exist in the namespace 'Unity' (are you missing an assembly reference?)

leaden ice
#

Is DVConnection your code?

elfin wedge
#

Yep

leaden ice
#

Do you have an asmdef?

elfin wedge
leaden ice
#

You don't know?

#

Check

#

it's an asset, in your asset folder. Assembly definition file

elfin wedge
#

I do not appear to have one

leaden ice
#

webrtc does though

#

Their asmdef is listing specific platforms for the assembly to exist

#

I'm not sure exactly how asset bundles work but... seems like their assembly is not included when building the bundle

elfin wedge
#

Hmmm

leaden ice
#

Do you pick a target platform when making an asset bundle?

#

(I've never done it)

elfin wedge
#

I'm learning about the asset bundle right now, so I can't say for sure lol. Been running into issues immediately

#

but I believe so

#

"Build Target"

leaden ice
#

whats in advanced settings

elfin wedge
#

this is what I see when I open the Unity Asset Bundle Browser tool

#

A bunch of errors after I attempt to build (from missing unity.webrtc)

glad mirage
#

Anyone has any idea how to save a GameObject that was created in PlayMode along with all its components? I was taking a look at this https://github.com/inkle/Unity-Save-Play-Mode-Changes/blob/master/Assets/PlayModeSaver/Editor/PlayModeSaver.cs but holy shit his code is dogwater

GitHub

Unity tool allowing changes made in play mode to be restored upon stopping the game. - Unity-Save-Play-Mode-Changes/PlayModeSaver.cs at master · inkle/Unity-Save-Play-Mode-Changes

leaden ice
#

then paste in edit mode

glad mirage
#

yeah, but i want my tool to be seamless.

leaden ice
glad mirage
#

you can? what's the API

glad mirage
#

ok lemme try

#

FUCK it works

#

thanks alot. i wish i knew this earlier. there goes 5 hours :c

warm shadow
#

Does anybody know why im getting these errors when i try to build my game?

simple egret
#

One of your scripts references Editor stuff, it's not possible in a build.

#

You'll need to exclude it from the build (put it in an Editor folder for example)

grim marlin
#

I made a function, for my player mouvement (first person), It works but I think their are some big problem on it ? Would someone be available to help me fix/review it in a quiet place ? ❤️

#

I would like to have a good base to start my project.

simple egret
#

You can create a thread if you're afraid more conversations would bury your questions

warm shadow
simple egret
#

No, anything under the UnityEditor namespace

warm shadow
#

so it needs to say Using UnityEditor

simple egret
#

Yes

warm shadow
#

okay

#

ill check

simple egret
#

The error has the faulty script btw

#

ToolsManager, line 6

warm shadow
#

ohh i see, that weird, i dont even use that, anyways thanks a lot

viscid kite
#

question so i've been creating new scriptable objects in runtime via constructor rather than create instance function. Is there issue i should worry about for continuing to do it this way?

craggy totem
#

Hello can someone help with Rotations,
I want to rotate Car's shadow (plane) according road's Normal (Raycast). shown in GIF (20mb can take some time to load)
Rotation along Axis Z and Axis X works as i wanted, but i can't find how to make axis Y repeat after RayCast (Car) gameObject rotation. thx

simple egret
grim marlin
viscid kite
simple egret
simple egret
meager crown
#

Is there a channel with people looking for partners/teammates? (sorry if this is the wrong place)

simple egret
meager crown
#

oh ok thanks

cyan hill
#

hi all, i've added movement, but i'm getting stuttering when moving. the stuttering also seems a bit random and not really at specific points each time. why might this be?

video: https://streamable.com/gfsxrb

the way i'm doing it basically has each tile as a cube object and i'm re-parenting the character object into each tile along the way. i then have an Update() on the character object to do a MoveTowards localposition of 0, 0, -2 (to stand on top of the tile). the re-parenting is part of a co-routine.

  1. pathfinding finds a specific ordered list of tiles to move through, to avoid objects
  2. re-parent the character to the next tile, delay, repeat til the end
  3. meanwhile as above ^ : keep updating the character's local position to 0, 0, -2, with MoveTowards

i've also tried it with packing the movetowards into a while for when the position isn't equal to the target.

both codes here: https://pastebin.com/2si5Vk74

viscid kite
#

for me at least since i need to not only create it but also create it based no parameters

#

still glad to know there's no major ramification for doing so

simple egret
#

I would still use CreateInstance myself though. If you choose to use new test thoroughly especially in a build, where their "save" behavior is different

full bluff
simple egret
#

You can't Destroy a ScriptableObject instance because it doesn't live in a scene

full bluff
#

ups i overlooked that you were talking about scriptable objects

#

It just jumped out at me since i had struggle destroying an object which i created through a "regular" c# class

leaden solstice
#

You can Destroy SO. Like how you destroy Sprite or Material. It's cleaning up C++ side resource of UnityEngine.Object

wild vigil
#

How would I paint mesh objects into the scene with a brush?

grim marlin
#

Basic First Player Camera/Movement Debug/Review

potent sleet
leaden ice
#

How do I make Rider stop preferring System.Numerics?

late lion
leaden ice
#

Can I make it forget

#

I've not once used Numerics on purpose

#

looks like they're using machine learning for the suggestion order

#

😢

clever spade
#

I updated to 2022 and I've notice that annoying feature. It also automatically inserts namespaces if I accidentally tab to their suggestions

leaden ice
#

Unchecking "Sort completion suggestions based on machine learning" fixes it. Go away silly machines

late lion
#

Hmm, mine is disabled for C#, but I've never seen this setting.

leaden ice
#

I have a fresh install, guess it's defaulted on now

clever spade
#

seems to work now

#

I'm still getting AI assisted recommendations on a new line even after disabling though, there's a cache somewhere and I don't feel like hunting that down Nevermind restarting visual studio cleared it

leaden ice
#

(I'm talking about Rider btw)

clever spade
#

They both have machine learning assistance

faint scroll
#

i get following error trying to set up velocity over lifetime of my particle system:

Particle Velocity curves must all be in the same mode
Code:

var vel = children.GetComponentInChildren<ParticleSystem>().velocityOverLifetime;
//vel.space = ParticleSystemSimulationSpace.Local;
AnimationCurve curve = new AnimationCurve();
curve.AddKey(0.0f, 1.0f);
curve.AddKey(1.0f, 0.0f);
vel.y = new ParticleSystem.MinMaxCurve(-180 * Throttle, curve);
vel.x = new ParticleSystem.MinMaxCurve(0,0);
vel.z = new ParticleSystem.MinMaxCurve(0,0);

Can someone help me here?

clever spade
faint scroll
#

i just got it, i simply didnt pass a curve but two times a value

clever spade
#

but I'm not sure if that would use a default set by you or an actual empty curve

swift falcon
#

hello does anyone know how I can turn off the autofill in vs

simple egret
#

There is a small purple button at the bottom-left of the code view, you can control it from here

swift falcon
#

thanks!

modern creek
#

My android performance feels a little sluggish. Is there any unity functionality/libraries/api to get the framerate on Android (or any) device? Or do I need to roll my own and count updates?

void basalt
#

using the unity editor

modern creek
#

Hm, I haven't done that before.. I'll try, though. My own personal phone does weird shit when I try to put it into debug/usb mode (spam disconnects/connects in windows), but I was more hoping to start by verifying that the framerate is <60 or <30 or whatever the target framerate is for some of my team's devices.

regal marsh
#

I have limited experience working with navmeshes. is there a way to only have an agent move towards the target if the target is within a certain distance of the agent? it's a zombie horde game so i don't wanna check that on too many zombies at once in update because it might affect performance.

leaden ice
edgy lynx
#

How do you all manage your events?
For a brief example, let's say I had:

public class ShootController : MonoBehaviour
{
    public delegate void OnPlayerShoot();
    public static event OnPlayerShoot onPlayerShoot;

    public void OnShoot(InputValue _) // Using Unity's Send Message Input System
    {
        // shoot bullet code.
        onPlayerShoot?.Invoke();
    }
}
public class CameraShootEffect : MonoBehaviour
{
    private void OnEnable() => ShootController.onPlayerShoot += CameraShake;
    private void OnDisable() => ShootController.onPlayerShoot -= CameraShake;
    public void CameraShake() => Debug.Log("Shake camera");
}

In order for this to work, I would have to drag the CameraShootEffect.cs onto an empty object in the scene. So do you just create like a DDOL EventManager empty GO, that holds all your event data? Or what's a manageable approach to this?

leaden ice
#

In that vein, I attach event listeners local to where their effects will be

edgy lynx
#

Awesome, thanks Praetor. Yeah, that makes complete sense, I kinda rushed the question out while it was fresh in my mind lol

leaden ice
#

Another example: a UI health bar could listen for HealthChanged events, and would live on the health bar ui

vagrant blade
#

My events are on the Controller script of an object. If that object has components which are local functionalities, they'll call a function on the controller to call the event.

#

That way everything outside the controller only has to deal with that controller.

woeful leaf
#

So I've this OnEnable

    private void OnEnable()
    {
        buttons = GetComponentsInChildren<Button>();
        for (int i = 0; i < 2; i++)
        {
            buttons[i].onClick.AddListener(() => Modify(buttons[i], Variable.Volume));
            print($"Index: {i}, Button:{buttons[i]}");
        }
        for (int i = 2; i < 4; i++)
        {
            buttons[i].onClick.AddListener(() => Modify(buttons[i], Variable.Level));
            print($"Index: {i}, Button:{buttons[i]}");
        }
    }

Which prints out the appropriate assigned buttons just fine. But when I run print(Array.IndexOf(buttons, button)); (the first line within Modify) it gives 2 for the top 2 buttons and 4 for the bottom 2 buttons. Any ideas as to why this could be happening?

woeful leaf
woeful leaf
#

Ah

#

I've had this same exact issue before

woeful leaf
# woeful leaf So I've this `OnEnable` ```cs private void OnEnable() { buttons ...

Doing this instead of the other fixes it

private void OnEnable()
    {
        buttons = GetComponentsInChildren<Button>();
        for (int i = 0; i < 2; i++)
        {
            int j = i;
            buttons[j].onClick.AddListener(() => Modify(buttons[j], Variable.Volume));
            print($"Index: {j}, Button:{buttons[j]}");
        }
        for (int i = 2; i < 4; i++)
        {
            int j = i;
            buttons[j].onClick.AddListener(() => Modify(buttons[j], Variable.Level));
            print($"Index: {j}, Button:{buttons[j]}");
        }
    }
#

I don't know why, but it does work, and that's how I've fixed a similar issue in the past as well, which this idea was given in the first place there at that point

#

If someone could explain why that is how that works though, that'd be great

leaden ice
quartz folio
woeful leaf
#

Thanks! I'll look into it!

woeful leaf
#

I get it now, thanks a bunch!

woeful leaf
quartz folio
#

If you do have things that act weird that you can condense to a plain C# example https://sharplab.io is a great resource

grim marlin
swift falcon
#

i need help

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;

public class TwoHandGrabInteractable : XRGrabInteractable
{
    public List<XRSimpleInteractable> secondHandGrabPoints = new List<XRSimpleInteractable>();
    // Start is called before the first frame update
    void Start()
    {
        foreach (var item in secondHandGrabPoints)
        {
            item.onSelectEnter.AddListener(OnSecondHandGrab);
            item.onSelectExit.AddListener(OnSecondHandRelease);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnSecondHandGrab(XRBaseInteractor interactor)
    {
        Debug.Log("Grab");
    }

    public void OnSecondHandRelease(XRBaseInteractor interactor)
    {
        Debug.Log("Grab release");
    }

    protected override void OnSelectEnter(XRBaseInteractor interactor)
    {
        Debug.Log("First Grab");
        base.OnSelectEnter(interactor);
    }


    protected override void OnSelectExit(XRBaseInteractor interactor)
    {
        Debug.Log("Exit Grab");
        base.OnSelectExit(interactor);
    }



    public override bool IsSelectableBy(XRBaseInteractor interactor)
    {
        bool isalreadygrabbed = selectingInteractor && !interactor.Equals(selectingInteractor);
        return base.IsSelectableBy(interactor) && isalreadygrabbed;
    }
}
#

it says no suitable method to override but there is

clever spade
#

need to see XRGrabInteractable

swift falcon
#

wdym

clever spade
#

also use a pastebin site instead of taking the entire screen

swift falcon
#

eh true

swift falcon
clever spade
#

Nevermind, looked it up myself. Make sure you spelled everything correctly

#

and you'll be fine

swift falcon
#

but

#

i cant find any mistakes