#archived-code-general

1 messages · Page 239 of 1

jolly dune
#

do you need transform?

rigid island
jolly dune
#

ok do you know what the issue is this is really bizarre

rigid island
#

try also printing the end result like movementVelocity

jolly dune
#

that works as intended except no z value

somber nacelle
#

you are using Vector2 rather than Vector3

jolly dune
#

yikes

rigid island
#

oof how i missed that too

#

unity just turns the v3 into a v2 and 0s the z 🥲

jolly dune
#

yea

#

now I need to clamp the values which is gonna be a pain

rigid island
#

V3clampmagnitude

jolly dune
#

well no I have to make it stay inside a placing area

rigid island
#

thats even easier

jolly dune
#

I'm making a 3D version of the watermelon games except instead of fruit it's gonna be my classmates faces

jolly dune
rigid island
jolly dune
#

yea but I don't know how to properly acsess the transform values

jolly dune
#

my favorite thing is going "well that didn't fing work" after every fail because it lessens the pain with a laugh

cunning radish
#

Hoping this is a good place to ask this, but is it possible to add a white tint to a sprite? Kind of like how you can tint a sprite with the unity sprite renderer, but since the rgb values there are by deafult at 255, and also capped at this, I can't make the sprite anymore "white". Not looking for a full solid white, just a tint.

rigid island
#

like what a flashing effect?

rigid island
# cunning radish Hoping this is a good place to ask this, but is it possible to add a white tint ...

Unity Asset Store BLACK FRIDAY Sale - EVERYTHING on this page is 70% off:
https://assetstore.unity.com/?flashdeals=true&aid=1100lwgBQ

Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquat...

▶ Play video
cunning radish
native folio
#

await AuthenticationService.Instance.SignInWithUnityAsync(accessToken);

What the hell is the access token??

rigid island
#

did you peep my vid?

native folio
#

i was gonna do username/password authentication but im too lazysooo kekw

native folio
#

send link

native folio
#

let me try the link version

rigid island
# native folio

the access token is there when user was signed in via browser uri

native folio
#

i ahvent signed in before tho

rigid island
#

hence the subscription to the Signed in event

#

watch the whole vid if you're doing Unity player accounts, i go through it pretty much in less than 10 min

native folio
#

ok

#

btw i recommend either using ur own voice or not having any voice at all

#

the robot voice is very anoyying

#

and i notice the mic is unmuted

rigid island
#

next vid coming up it uses this + the Code link which is signing the same account on another device using a code only

rigid island
polar marten
#

This surprisingly crashes my game

mellow dove
#

Which approach would you use to draw these arrows dynamically at runtime? (ie. in the example, they represent physics forces and animate on FixedUpdate())

cursive moth
#

maybe a line renderer but that prob wouldn't explain the arrows at the tips

jade bison
#

Hi, I'm facing a very weird issue. I have no idea how to fix it.

#

[DELETED]
↑ this is a dumb script I wrote

#

Whenever I add it to a normal (empty) GameObject in the scene, then, as soon as I try playing from the editor, my object becomes permanently infected with a RectTransform thereafter, replacing its regular Transform component.

#

this then stays that way when I stop playing and get back to the Editor (I believe one warning appeared when entering Play Mode, the other one when exiting~)

#

Why does that happen and how can I prevent a RectTransform replacing my Transform, for objects equipped with this script?

#

Using version 2021.3.9, by the way!

#

Do not hesitate to ping me if you've got any clues ^^

#

Also, googling did not help me much, I only encountered the one person seemingly using a Mask, or whatever UI thing it was, in their script, thus tricking Unity into believe that this object was meant for a UI canvas. If that's the case here… I can't see it? Where would the problematic object be in there?

jade bison
#

aaaand now the issue just won't happen again -_-

#

fixed I guess! ^w^
but yeah weird, no idea what causes it

fallen pollen
#

Can someone help me with my unity 2d project? I cannot seem to make it that whenever the sprite goes left and right they start the walking animation.
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
public Animator anim;
public Rigidbody2D myRB;
private SpriteRenderer spriteRenderer;
[SerializeField] public float speed;
private void Start()
{
anim = GetComponent<Animator>();
myRB = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
}

private void Update()
{
    myRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
    spriteRenderer.flipX = myRB.velocity.x > 0f;
}

}`

#

If you want to see my ingame unity settings lmk

somber tapir
fallen pollen
#

yeah i dont know how to haha

#

Ive set the animations up in the animator, adding conditions. I have no clue what to do from there..

somber tapir
fallen pollen
#

Can u explain the code for me. So im not just putting in code that idk. I actuallt kmow so i can do this for next time

somber tapir
# fallen pollen Can u explain the code for me. So im not just putting in code that idk. I actual...

anim.SetBool(). Sets a bool condition on the animator to whatever value you put in as the second parameter.
'myRb.velicity.magnitude' is the "length" of your velocity, i.e. 0 when there is no movement and higher than 0 when there is. Basically how fast it is going. by writing
(myRb.velocity.magnitude > 1) we create a bool that is true when the magnitude value is greater than 1 and false if it is lower.
So the code is: Set the bool condition on this animator named "isRunning" to true if the RB has some velocity, and to false if it doesn't.

fallen pollen
#

Thank you so much 🙏

fallen pollen
open charm
#

Got a question about a dont destroy on load gameobject

somber tapir
fallen pollen
open charm
#

So currently I have this scene that has a UI button gameobject that has an OnClick function tied to enother gameobject. The problem is that that other gameobject has the Dont DestroyOnLoad and if there is a duplicate itll destroy the copy, this means that the UI button's OnClick function wont work cuz the other gameobject is missing. How do I reassign the other gameobject to the ui function?

fallen pollen
somber tapir
fallen pollen
#

Alright ty

wise pumice
#

Can anyone help me with this?

I made a script so that my player is teleported to a certain position if they fall off. But the camera keeps bugging out and seems to try to follow etc, but I just want it to snap back with him

vagrant agate
# open charm So currently I have this scene that has a UI button gameobject that has an OnCli...

I'll be honest, you shouldn't be connecting ui elements to a ddol object/singleton. You should be thinking of another object oriented way to go about what you are doing.

But if you must do what you want, you need to attach a script to your button and set a static class reference to it so it's easily accessible, Instead of using game object find. Regardless of how you end up finding the button again, you just need to call remove all listeners on the button and then add the on click listener to point back to your function.

open charm
#

Im still new with how OOP works

hexed pecan
vagrant agate
#

In short, "most" ddol's are used as managers/singletons for utility classes, persistence session game state, etc. Or when the ddol object script relies on itself or its children only. It shouldn't have relation to any objects not within itself when moving scenes so it doesn't lose references.

I'm not saying you can't do what your doing and it be fine.

open charm
#

whats ddol again?

maiden quail
open charm
#

oh right ok

#

So what ur saying is that ddol objects must be independent from any other element aside from their own children?

jolly dune
#

I've never had issues with VS code not responding and not it is completely broken what should I do

vagrant agate
jolly dune
#

can't even close unrelated programs but some work like discord/chrome

open charm
#

As in like

#

When should I use it

maiden quail
vagrant agate
open charm
#

I havent used OOp in a while

#

Ill looks into ti

worn oasis
#

Hey all, we installed HDRP recently and we're getting this error:

scarlet viper
#

Can I load the same scene additively many times via code ?

maiden junco
#

Is it better to create an interface or to write a class for Interactables?

#

I've seen programmers use both designs

gray raft
#

Have seen player holding this board in game, its toggles there is animation how its being made,
Is it just simple animation of gameobject or something else?
And also how paper on text fits well with the Game object any help?

maiden junco
gray raft
#

might be a dump question to ask haha can we add multiple canvas like one for Overlay and one for World Space

somber tapir
somber tapir
maiden junco
#

I've made an Interactable class which has a OnInteract UnityEvent and a bool canInteract

#

and i just inherit it to all my interactable classes

somber tapir
# maiden junco I wanted to add a few parameters to each interactable, but I don't think that it...

You could have a class called 'InteractableData' and pass that as parameter. Then you can either add variables to it or inherit it and create specific data for each interactable, i.e. DoorData. The only problem with that is that you need to cast it to the correct type before you can use it.
But there should never be a reason to get the gameObject in the first place, since NPCScript has a reference to it anyway.

dawn mauve
#

It does an awful job of explaining how to start a custom package and what it looks like to develop one.

For the custom package manifest it doesn't tell you what its supposed to look like; one has to grok 3 pages of documentation to know what it is supposed to be. Even then, there are so many questions you have to read in between the lines for.

It's laughably bad.

somber tapir
dawn mauve
hoary pewter
#

how should I go about clamping the Z rotation of my object between e.g. -40 and 40 degrees

#

this just makes it permanentally stuck at -40

somber tapir
hoary pewter
#

oooh right

somber tapir
#

You might have to subtract 180, then clamp, then add 180 back

#

there are probably also functions that handle exactly that, but I don't know them

scarlet viper
#

how to get reference to loaded scene other than OnSceneLoaded and GetSceneByName/Index/Path ?

#
           AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene2");
            while (!asyncLoad.isDone)
            {
                yield return null;
            }
            asyncLoad.

can i get reference to scene from asyncLoad ?

#

i load multiple scenes with the same name so GetSceneBYName doesnt work.

scarlet viper
#

thats problematic cause i cant pass a param to OnSceneLoaded either

polar marten
#

how should I go about clamping the Z

#

how to get reference to loaded scene

#

It does an awful job of explaining how

hard viper
#

can someone explain to me:
public interface IMyInterface<out T>

#

I've looked it up at least 4 times, and I never understood it

dawn mauve
#

@polar marten you need to make sure you read and understand messages before you attempt to "answer" to ensure you aren't hallucinating

vagrant agate
hard viper
#

yes

#

I just don't understand how the <out T> works vs just normal generic <T>

#

and vs normal non-generic interface

delicate zinc
#

I have all these rooms generated on Start via procedural generation, is there a way i could bake occlussion stuff post generation?

#

or would i need to come up with my own occlusion solution for htat?

maiden junco
#

This image describes perfectly its behavior

hard viper
#

how does this work when writing the interface then?

plucky cobalt
#

ok i have a better idea.

maiden junco
# hard viper how does this work when writing the interface then?

Lets pretend that you have:

class Fruit {}

class Banana : Fruit {}

interface ICovariantSkinned<out T> {}

interface ISkinned<T> {}

and the functions

class Program
{
  void Peel(ISkinned<Fruit> skinned) { }

  void Peel(ICovariantSkinned<Fruit> skinned) { }
}

The function that accepts ICovariantSkinned<Fruit> will be able to accept ICovariantSkinned<Fruit> or ICovariantSkinned<Banana> because ICovariantSkinned<T> is a covariant interface and Banana is a type of Fruit,

the function that accepts ISkinned<Fruit> will only be able to accept ISkinned<Fruit>.

hard viper
#

where is Peel defined

#

because this just looks to me like two overloads

maiden junco
#

i updated the example

plucky cobalt
#

i have a box trigger and i want it to whenever a player goes inside it, the door opens i made a bit of code to find out the problems with it and to make it work.

if ("Gorilla Rig") is inside of ("OpenTrigger") play anim ("DoorOpen") wait until ("DoorOpen") is finished then play ("DoorIdle)

again this is just simple code that i want to make work, how do i fix it?

maiden junco
plucky cobalt
#

sure

#

i sec

hard viper
#

i see. so how do I populate the interface differently when it is a Covariant interface?

#

the whole point of having the generic is to call methods depending on the type, after all

maiden junco
#

but if you gotta assign the same interface that is of type of a class A to a type B you gotta put the out keyword in front of the generic

plucky cobalt
maiden junco
#

class A {}
class B : A{}

interface IMyInterface<out T> {}

IMyInterface<A> foo;
IMyInterface<B> = A; // This will compile since the generic its defined as out T
class A {}
class B : A{}

interface IMyInterface<T> {}

IMyInterface<A> foo;
IMyInterface<B> = A; // Compilation error

maiden junco
plucky cobalt
#

yeahj

somber tapir
# plucky cobalt yeahj

There are hundreds of tutorials on how to get started, I suggest you check them out first to learn the basics of C#

maiden junco
#

for checking trigger states of a gameobject you can use methods like OnTriggerEnter, OnTriggerExit and OnTriggerStay

#

for playing animations you could use an Animator and define some states on an animator layer (the base layer by default)

plucky cobalt
#

should i don what this says?

maiden junco
plucky cobalt
maiden junco
plucky cobalt
#

thats what it does

maiden junco
#

its a visual studio thing i guess

maiden junco
plucky cobalt
#

oh

maiden junco
#

i suggest you to watch some tutorials where they cover Triggers and Animations

plucky cobalt
#

i will

#

gotta get off tho tyty

spring creek
# plucky cobalt oh

You were already told this will never work. Not a single piece of this is valid nor makes sense. If you actually want help, take a lesson first, if you are just trolling (much more likely), just stop

hard viper
maiden junco
# hard viper so... how do I put a member into the interface to actually make use of the <out ...
public class Enemy { }
public class Boss : Enemy { }

public interface IEnemyProvider<out T>
{
    T SpawnEnemy();
}

public class EnemySpawner : IEnemyProvider<Enemy>
{
    public Enemy SpawnEnemy()
    {
        // Implementation to spawn a regular enemy
        return new Enemy();
    }
}

public class BossSpawner : IEnemyProvider<Boss>
{
    public Boss SpawnEnemy()
    {
        // Implementation to spawn a boss enemy
        return new Boss();
    }
}

And the implementation:

IEnemyProvider<Enemy> regularEnemyProvider = new EnemySpawner();
Enemy regularEnemy = regularEnemyProvider.SpawnEnemy();

IEnemyProvider<Boss> bossEnemyProvider = new BossSpawner();
Boss bossEnemy = bossEnemyProvider.SpawnEnemy();
hard viper
#

that helps. ty

#

and just to be clear, then you can't use T as the type of an input arg? because there's no way to know?

latent latch
#

I use convariance just because the compiler yells at me and I have to comply with it

hard viper
#

on that topic, is there a non-dumb way to do this:

    if (associatedPrefab.TryGetComponent(out ISimpleAutoTileMono<TilePlacementInstance> mono)) mono.AssertValid();
    else Debug.LogError(error_msg");
} else {
    if (associatedPrefab.TryGetComponent(out ISimpleAutoTileMono<TilePlacementContiguous> mono)) mono.AssertValid();
    else Debug.LogError(error_msg");
}```
#

where public interface ISimpleAutoTileMono<TTilePlacement> where TTilePlacement : ITilePlacement

#

I was wondering if I could make it simpler with Covariance, but that interface requires a method where the input is of type TTilePlacement

maiden junco
#

you could create a method that checks whether its Individual or not

#

void CheckAndAssertValid<T>() where T : class
{
    if (associatedPrefab.TryGetComponent(out ISimpleAutoTileMono<T> mono))
    {
        mono.AssertValid();
    }
    else
    {
        Debug.LogError("error_msg");
    }
}

#

and then

if (autoObjConversion == AutoTileToObjectType.Individual)
{
    CheckAndAssertValid<TilePlacementInstance>();
}
else
{
    CheckAndAssertValid<TilePlacementContiguous>();
}
maiden junco
#

like int, float, bool and so on

hard viper
#

I think that would work. Just checking options to avoid all the downcasting.

#

but I don't think it would work here, which is unfortunate.

humble void
#

So, there seems to be very little documentation about the new navigation package that's why I am asking around: I want to bake a navmesh on runtime but it takes a ridiculous ammount of time and it blocks my main thread, is there any way to move it to another thread? Can it be used with the jobs system? Can it be run asynchronously?

hard viper
#

one more interface question. I want an interface to only be attached to Monobehaviours, and I need everything that implements that interface to call the exact same method in OnDestroy. Is there a way for me to do this?

heady iris
latent latch
#

Probably want to use events for that, otherwise do it all in the base class

hard viper
#

I am thinking about how to do this.

#

maybe the interface should force the implementation of a property tied to an event, and then interface method can add something to it?

heady iris
#

One option would be to make your own class that subclasses MonoBehaviour

#

Give it virtual OnDestroy and Awake methods

hard viper
#

or maybe interface forces public void OnDestroy, and then interface can add a method to it?

heady iris
#

Have the class test if it's an instance of IWhatever and do the needed thing if it is

#

This feels gross

#

well, only a little gross

#
protected virtual OnDestroy() {
  if (this is IWhatever interfaceInstance) {
    interfaceInstance.Cleanup();
  }
}
latent latch
#

that's not too bad

#

I do something similar cause I can't be bothered sometimes

heady iris
#

now you just need to make sure you call the base method if you override the virtual method

hard viper
#

It is a generic interface, so it can't be put on a gameobject normally

#

must be made concrete

#

changing to a monobehaviour doesn't change that

heady iris
#

ah, I'm not sure what you could do, then

#

maybe reflection

hard viper
#

idk. maybe is there any way for an interface to force a class that implements it to call specific code?

hoary pewter
#
public void PlayerRot(float rotDirection)
{
        Quaternion targetRot = Quaternion.Euler(0f, transform.rotation.eulerAngles.y + rotSpeed * rotDirection, 0f);

        transform.rotation = Quaternion.Slerp(Quaternion.Euler(0f, transform.rotation.eulerAngles.y, -transform.rotation.eulerAngles.y), targetRot, rotSpeed * Time.fixedDeltaTime);
        isRotating = true;

        timer = 2;
        StartCoroutine(ResetRotationFlag());
  
    }
#

anyone got any idea as to whats causing the rotation to continue where it left off before resetting to 0?

hard viper
# heady iris maybe reflection

Possible workaround:


public class DestroyDetector : MonoBehaviour {
    public event Action DoOnDestroy;
    public void OnDestroy() => DoOnDestroy?.Invoke();
}
///// <summary>Remove self from entity ledger. </summary>
private void LogDestroyedObj() => EntityLedger.GetInstance()?.LogDestroyedEntity(gameObject, EntityLedgerCategory.Tile);```
#

too dumb?

#

feels wasteful to make a whole monobehaviour like this

hexed pecan
hard viper
#

I believe I am as far as unity allows

hexed pecan
#

Maybe a default OnDestroy method in the interface?
Havent used those myself, just throwing some ideas

hard viper
#

I'm not exactly sure how unity works with that tbh

#

I might make it an abstract generic class, but I feel like that might restrict my ability to make classes, since we can only inherit once

#

fuck it. I'll just make an abstract class

lean sail
#

I might be remembering wrong but the default interface methods would probably just cause your regular OnDestroy methods to not run at all. I say abstract class is exactly what you want here

hard viper
#

I'm just going to go with my standard pattern:
public abstract class SimpleAutoTileMono<TTilePlacement> : SimpleAutoTileMono where TTilePlacement : ITilePlacement {}
public abstract class SimpleAutoTileMono : MonoBehaviour {}

#

the latter class just being a convenient way to access the non-generic methods

heavy forge
#

I have a box that I want to move to my variable called mousePos (mouse position but kept within distance from the player). Using transform.position = mousePos works well except that it doesn't take in account other colliders. So I'm trying to use RigidBody2D.MovePosition(mousePos) but for some reason the box only moves on the y axis and not on the x... I have no idea why this isn't working as transform.position = mousePos does work and I'm not changing any code (except for the line where I move the box ofcourse) when I'm using MovePosition instead. Is this a common issue? Is there a better way to take in account other objects?

lean sail
heavy forge
#

What other way is there to do this then?

lean sail
# heavy forge What other way is there to do this then?

depends on what this is really for, either use non-kinematic rigidbody with addForce/velocity or move the transform but use physics casts to make sure nothing is in the way.
In your current setup, did you debug what mousePos is? I assume something was colliding with your object which is why it couldnt move on the X axis

heavy forge
#

mousePos is what I want it to be, a Vector2 "clamped" in a circle around the player. Nothing is colliding with the object, it just refuses to move on the x when using MovePosition. I'm assuming that isn't the way to do it then, but I'm also not sure if using velocities is a good idea. Because I want my object to just be at the mousePos rather than going there if that makes sense.

lean sail
heavy forge
#

I'll try it out tomorrow

plush basin
#

Hey guys, I have noticed unity does not seem to execute the Awake function in abstract classes - But I am pretty sure it used to do that in older versions.
I have an abstract class that handles some backbone of my management stuff and I need the awake method to be executed.

Do I need to find a workaround and if so what could that look like?

ionic adder
plush basin
#

Because what I have is an abstract class Manager containing a static reference to itself

public abstract class Manager : MonoBehaviour
{
    public static Manager Instance;

    private void Awake()
    {
        if (Instance != null)
        {
            throw new ArgumentException();
        }
        Instance = this;
    }
#

And in my thinking declaring this static instance of the manager would then force it to initialize the script, because now we have a static Manager that can be accessed from everywhere. But this Awake method is never called

latent latch
#

awake should be called

lean sail
latent latch
#

Oh, it's abstract so yeah you need to derive an actual class you can create an instance of

plush basin
#

But I'd really like to have this static Instance field so that anywhere in the project I can go

Manager.Instance.DoMagic();

Because then the actual management stuff can go in regular MonoBehaviours that sit somewhere in the scene. The Manager.Instance just handles handing out references to scripts that need them. This way I dont have to hardwire all the references or have all the management classes be static. But I see the error in my thinking now and will retry something else.

#

Ahhhh I am such a dud 🤣
Ofc, I am always only thinking on the code level and keep forgetting sometimes that theres a whole engine around my code. Thanks!

plush basin
#

But now I kinda wanna know how it would be done ngl

latent latch
#

Consider looking up a service locator pattern (basically just another abstraction layer for your singletons which allows for the implementation of a subscription/observer model) as this sounds like something you're trying to develop

plush basin
#

Oh thanks! Yeah Im not really well read on patterns at all yet. Thanks for the pointers!

spare scaffold
#

!code

tawny elkBOT
polar marten
#

Because what I have is an abstract class

#

i have a box trigger and i want it to

strange scarab
#
StartCoroutine(CleanUp(cube));

private IEnumerator CleanUp(GameObject cube)
    {
        // Doesn't yield past 5 for some reason?
        yield return new WaitForSeconds(4f);
        Destroy(cube);
        print("Cube destroyed? " + secondsBeforeCleaned);
    }
#

I have this function that works except it doesn't yield if I use anything more than 4 seconds and I'm baffled as to why

lean sail
strange scarab
#

it doesn't print at all if I yield any higher than 4 seconds but it does print for 1 2 3 or 4 seconds

lean sail
strange scarab
#

but the cubes still exist after that they just don't ddestroy

lean sail
#

Or maybe you set the timescale to 0 at some point

strange scarab
quartz folio
#

If you want to ask things directly of other users that are of no value to others, do it via DM

vernal wharf
#

Hi, my partner is looking to create procedural generated 3D caves, and I'm wondering if anyone knows anyone resources to help show how to do this. He's not interested in using Cellular Automata.

cosmic rain
terse turtle
#

Can I have a Tilemap Collider change Scene when colliding with player, but the scene is specific with the Door using SceneManager.LoadScene(). Town door would be a difference scene, Guild door would be a different scene, etc.

vagrant blade
#

You need to put some logic on the collider that defines what scene to go to and which spawn point in tihat scene to use.

terse turtle
rain minnow
terse turtle
vagrant blade
#

So change the scene on the collider to be a different one 🤷‍♂️

leaden ice
vagrant blade
#

How are you changing the scene now on two different exits?

terse turtle
#

This is the Code I have: cs private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject) { Invoke("SendToHouseScene", 0.5f); } } void SendToHouseScene() { SceneManager.LoadScene("Housing"); }

rain minnow
quartz folio
#

You have to move SendToHouseScene out of that function, to the class scope

#

also, use nameof(SendToHouseScene) to avoid explicit strings

terse turtle
quartz folio
#

also, if (collision.gameObject) will always be true

terse turtle
leaden ice
terse turtle
#

I should have mentioned. This is the code I am using, but I know it doesn't work for sending Player to Multiple Scenes* I need help finding the solution for that*

leaden ice
#

then you can just go to whatever scene the door says to go to

#

seems like a simple scalable solution

#

You can set the scene in the inspector for the door.

rain minnow
terse turtle
#

This is my layout of the map. The doors are highlighted, and are the ones I need to fix. They are all contained in one Tilemap called, "Door". I need each door to teleport to a different scene.

terse turtle
terse turtle
leaden ice
#

Or - have a map of tile coordinate to scene name somewhere

#

and look up the scene name based on the door coordinate

#

seems like a lot of maintenance though

terse turtle
#

Is there not a simpler and efficient solution outside of those two?

rain minnow
terse turtle
leaden ice
terse turtle
leaden ice
#

You can even use the GameObject brush on the tilemap

rain minnow
terse turtle
rain minnow
terse turtle
terse turtle
terse turtle
hard viper
#

imo, i would not use tilemap brush for anything but testing

#

if you want to make custon levels with tilemaps, you should use Tiled. If you just want to use tilemaps to represent things programatically, you don’t need a brush either

round violet
#

hey
in Unity is there a interface system (maybe its not the same name as UE) ?
Like you have a "asset" or script that contains a list of functions with inputs and outputs, you can then add it to any object in game
then from another game object, you can check if this interface exist and call the functions, but no errors occurs if the function doesnt exist in given game object

tell me if i wasnt clear

note: after writing this message, it feels like a "interface" in Unity would just be a c# script

cosmic rain
#

Sounds like it.

#

Unity events might help you reference methods in the inspector

round violet
#

how would this part work but no errors occurs if the function doesnt exist in given game object ?

cosmic rain
simple sable
#

Hey. Not sure if this is the right channel to ask and it's probably a dumb question, but yeah.
I was wondering why the second " and ) have a lower opacity than the first? (I'm using Visual Studio 2019). Reason I'm asking is because I know that, when I use brackets where not needed or "this.", etc., they get like that too. But not sure why they do here tho.

cosmic rain
#

I'm surprised you've even noticed it.
Maybe minutes implicitly converts to string with this parameter?🤔

simple sable
#

Oh, you might be right actually.

oblique spoke
#

Highlighting over these should tell you why it's showing you this

knotty sun
modern magnet
#

hey everyone, i cannot figure out as to why the tile left of the king does not highlight, even though all the others do

#

how do i post code?

oblique spoke
tawny elkBOT
modern magnet
modern magnet
# oblique spoke !code

i tried to copy paste it but it automatically converts to a .txt file, must be cause there are too many lines

mellow sigil
#

You have (-1, 0) twice in the list of valid movements

modern magnet
#

🤦‍♂️ such a silly mistake
thanks for letting me know

#

i was also wondering if there is a way to reduce the if else statements in the row column check function

mellow sigil
#

For one you don't need a special case for column and row 0. The second for loop just won't run in that case anyway.

#

same for column/row 7 actually

steady moat
# modern magnet i was also wondering if there is a way to reduce the if else statements in the r...

You could also merge the concept of checking row and diagonal in a single for loop.

List<(int dx, int dy) straights = new List<(int x, int y)>() {(1,0),(-1,0)(0,1),(0,-1)}
List<(int dx, int dy) diagonals = new List<(int x, int y)>() {(1,1),(-1,1)(-1,1),(-1,-1)}

foreach((int dx, int dy) direction in straights) 
{
  for(int i = 1; i < 8; ++i)
  {
      (int x, int y) position = (currentX + direction.dx * i, currentY + direction.dy *i);
      if(IsValid(position))
        AddToValidPosition(position);
      else
        break;
  }
}
modern magnet
#

where does the diagonals list come into play??

modern magnet
mellow sigil
#

Presumably you added those special cases because you don't want the second (or first) loop to run on those columns/rows, right? Well they don't run anyway on them so they're just unnecessary

steady moat
# modern magnet where does the diagonals list come into play??
List<(int dx, int dy) straights = new List<(int x, int y)>() {(1,0),(-1,0)(0,1),(0,-1)}
List<(int dx, int dy) diagonals = new List<(int x, int y)>() {(1,1),(-1,1)(-1,1),(-1,-1)}

List<(int dx, int dy)> availableMoves = new List<(int x, int y)>();
availableMoves.AddRange(straights);
availableMoves.AddRange(diagonals);

foreach((int dx, int dy) direction in availableMoves) 
{
  for(int i = 1; i < 8; ++i)
  {
      (int x, int y) position = (currentX + direction.dx * i, currentY + direction.dy *i);
      if(IsValid(position))
        AddToValidPosition(position);
      else
        break;
  }
}
mellow sigil
#

For loops check the condition before the first loop and just do nothing if the condition is already false

hard viper
#

that notation works?

#

shit I’ve been using the tuple class, which is so confusing to understand later

modern magnet
#

the pieces that are not on the edge require both sides to be checked thus i did this

mellow sigil
#

Right but the "normal" case already skips the other direction there

#

so there's no point in making a special case

hard viper
#

so if you have a 5x5 board, I make a 9x9 array or something, that automatically offsets itself when you access

#

then you don’t need to check edge cases, which are obnoxious

modern magnet
hard viper
#

you just need to check for null, which you would do anyway

#

idk if this helps for your case

modern magnet
hard viper
#

i have a lot of systems in my game that are on a grid, and I really don’t want to constantly deal with edge cases. a padded matrix helps me keep my code much simpler

#

let me see if I can send you simple code on git

hard viper
#

sure. the docstrings should make it clear enough how to use

steady moat
modern magnet
#

no, i meant why not use i++?

hard viper
#

++i is the awkward cousin of i++

steady moat
#

In other words, I'm doing it so I don't have to hear that from other team member

modern magnet
#

but doesn't using ++i cause the loop to offset by 1?

modern magnet
#

or am i wrong

hard viper
#

i don’t think so

modern magnet
#

ooh

hard viper
#

++i is just awkward when people use the ++ in the middle of a line where other things are happenning for some reason.

steady moat
#

It is like if you did:
some instruction;
++i;
some instruction;

maiden junco
#
int a = 5
Debug.Log(i++) // OUTPUT: 5
int a = 5
Debug.Log(++i) // OUTPUT: 6
fervent furnace
#

++i is faster than i++ a bit since no temporality register is needed to store the value before increment
the compiler will optimize it

hard viper
#

so effectively no difference unless you call it in the middle of a line

#

with other things going on, as above

#

in which case what it does is actually just different

fervent furnace
#

it is true for almost all cases unless you start to use pointer....

hard viper
#

I left that life behind. I never want to see another pointer ever again

#

the seg faults and memory leaks scarred me

#

Tile question. I have a design for a tile that requires corners in terms of rule tiling. By symmetry, I have a little border that I could express with ~12 tiles (with different rotation/mirror symmetry). And a design inside that can’t be rotated, but can be expressed with maybe 9 tiles tops? If i have no symmetry, this would be like making 256 tiles, which is way too much.
Q: Is there a way to make a tile that displays like two tiles overlaid on each other?

cold egret
#
  • If i create an enumerator object once, can i re-use it to start multiple coroutines? Will they work when started simultaneously?
hard viper
#

one instance? i don’t think so

#

Ienumerators do things by calling:
while (enum.MoveNext()) yield return enum.Current

#

if you have one enumerator, every MoveNext() call will advance it

#

unless start coroutine makes a copy? but it’s a reference type, so i don’t imagine so

cold egret
#
  • That's what i assumed. So if i ensure that one enumerator is only ever used once, i can reuse them by invoking reset on them first?
leaden ice
leaden ice
#

What you can do is save a reference to the coroutine function itself in a delegate, and call that repeatedly

#

E.g. cs Func<IEnumerator> example = MyCoroutine; StartCoroutine(example()); StartCoroutine(example()); StartCoroutine(example());

cold egret
#
  • Which will still create new enumerator objects per call, but also cause extra overhead for delegate objects storage. The problem is garbage allocation in the project that relies on coroutines heavily, not the access to the methods
leaden ice
#

There is no way to avoid allocation with coroutines

#

If you want to avoid allocation, do not use coroutines

cold egret
#
  • I see. Unfortunate, but the only way to go ig. Thank you
hard viper
#

as far as I understand, the main coroutine garbage is the new WaitUntil etc instances

leaden ice
#

The enumerator itself and the Coroutine object are also allocated

heady iris
#

executing a method that returns an enumerator creates garbage

#

because an instance of a compiler-generated class has to be created

hard viper
#

aren’t both those two objects super light tho?

leaden ice
#

They are light but if your goal is zero allocation they aren't zero

hard viper
#

drop in the bucket imo

#

unless you spam them, everywhere. which has its own host of issues

#

but that becomes an architecture issue, not an allocation issue

cold egret
#
  • Even drops in a bucket eventually will fill it. Besides, the project i've been asked to optimize throws not drops and not even spoons but other buckets
cold egret
hard viper
#

coroutines are not where I would start optimizing

#

corotuines would be more a target to straighten things out

#

what I mean is that the use of coroutines isn’t going to be what crushes performance. it’s probably what they are doing

cold egret
hard viper
#

god damn wtf bro

cold egret
#
  • Ikr
hard viper
#

why do you have so many coroutines

#

i have one class that might be helpful

cold egret
hard viper
#

this is a very helpful class that helps me cut down on coroutines

#

it's a singleton with an extremely late early execution order. A lot of coroutines exist because you just want to execute one line on the following frame.

#

in those cases, I just subscribe a function to one of the delegates of this singleton

cold egret
#
  • Events also create garbage fyi. Sometimes less than coroutines, but it's not guaranteed
hard viper
#

they should be mostly like function pointers

#

it makes a bigger difference if you have a coroutine with a while....yield return new WaitForFixedUpdate(); loop

#

because that shit makes garbo every fixed frame.

#

and it's a bit simpler to set something to execute just once with this pattern

#

given your case is a doozy, it is one option that might help

latent latch
#

events making garbage is pretty surprising to me

#

i need to cut down of mine later on because of it

cold egret
#
  • The smallest single target delegate contains at least function and instance pointers, then you get parameters and local variables in the instances of the generated classes that they might point to additionaly to your type. Besides, delegates are immutable and will always reallocate when you add/remove something
hard viper
#

I think he's refererring to the garbo that comes from actually calling delegate Combine

#

maybe this is worth benchmark testing.

latent latch
#

im thinking of making my own event system and just deal with pointers myself

hard viper
#

if you need to really optimize, maybe making a List<Action> might be useful. Then a singleton holds a block of memory that stays allocated

#

List<Action>, then .Add, .Clear, .GetEnumerator....

#

instead of +=, =null, ?.Invoke()

#

again, just lighter. people rarely make coroutines for the fuck of it. it's almost always because there is some timing aspect that needs to be respected.

cold egret
cold egret
latent latch
#

the benefit of coroutines is sleeping them and getting somewhat accurate wakeup times

#

otherwise I'd just do it all in a single updateloop and poll them

#

so runtime performance vs some garbage

#

which equates to performance too, but effectively polling hundreds through update is probably the worse of two.

modern magnet
#
for (int i = column + 1; i <= 7; i++) // check in the right side 
{
    if (!IsOccupiedByWhite(row, i) && !IsOccupiedByEnemy(row, i))
    {
        _listOfTilesToHighlight.Add((row, i));
    }
    else { break; }
    if (IsOccupiedByEnemy(row,i))
    {
        _listOfTilesToHighlightRed.Add((row,i));
    }
}

Will the break cause the loop to exit without checking for the IsOccupiedByEnemy?

fervent furnace
#

you have two IsOccupiedByEnemy here

latent latch
#

break exits any loop you use it in

#

at that point

modern magnet
#

i want to check whether the tile is occupied by enemy or not as well

polar marten
latent latch
#

continue? actually you probably have that statement below for a reason haha

#

not sure of the use case here

mellow sigil
#
if (IsOccupiedByEnemy(row,i))
{
    _listOfTilesToHighlightRed.Add((row,i));
}
else if (!IsOccupiedByWhite(row, i))
{
    _listOfTilesToHighlight.Add((row, i));
}
else 
{ 
    break; 
}
modern magnet
# polar marten why do you have `else { break; }`

if a tile is occupied by a piece, suppose a white piece, in that case, i do not have to check further since i can only highlight till that point thus using break to immediately break out of the loop

polar marten
#

maybe start by correctly enumerating a tile's adjacent tiles

modern magnet
polar marten
round violet
#

i cant find a way to use a custom enum as the keys of a dictionnary

//global
public enum ElementsType
{
    None,
    FloorBox
}

// in class
private Dictionary<ElementsType, int> _actions = new Dictionary<ElementsType, int>()
    {
        ElementsType.FloorBox = 1
    };

what could be the issue ?

latent latch
#

why not just use the enum if you're doing int to int

round violet
#

int is a temp test

#

i will replace with functions

latent latch
#

probably need to use brackets []

round violet
#

im debuggin step by step

fervent furnace
#

ElementsType.FloorBox is a constant and you cannot assign a constant

round violet
fervent furnace
#

you can set the enum value in its declaration.....

latent latch
#

im pretty sure you can

fervent furnace
#
public enum A{
  a=10;
}
hard viper
round violet
fervent furnace
#

a named int

#

or byte , or long

round violet
#

so you cant make a dict using enums as key

#

is there a workaround ?

mellow sigil
#

You're just initializing the dictionary wrong

#
{
    { ElementsType.FloorBox, 1 }
}
fervent furnace
#

you can, but it is better to use an array and assign it by index
{key,value}

round violet
#

you mean using the int in the enum as the key to access whatever in the array ?

round violet
#

but i still got one of the errors

mellow sigil
#

Show code

fervent furnace
#

array[enum]=something or
something=array[enum]
and set the enums' value sequentially, start by 0

latent latch
#

it's brackets

#

yeah

round violet
# mellow sigil Show code
private Dictionary<ElementsType, int> _actions = new Dictionary<ElementsType, int>()
    {
        { ElementsType.FloorBox = 1 }
    };


fervent furnace
#

it is , not =

mellow sigil
#

That's not what I showed is it?

latent latch
#

[ElementsType.Floorbox] = 1

#

try that

round violet
#

im tired, sorry

round violet
#

well now i got some issues with storing a function as a key

latent latch
#

you make key to delegate

round violet
round violet
mellow sigil
#

That thread is about functions as values

latent latch
#

the value is the delegate

#

having a delegate as a key doesn't make too much sense

mellow sigil
#

What exactly are you trying to do? Having functions as keys is ... peculiar to say the least

hard viper
#

oml he was right. giant delegates have massive cost to +=

latent latch
#

ye need to make your own pointer management script

#

imma make one eventually because I bind and unbind tens-hundreds of event per item equipped

#

pretty expensive

round violet
glass berry
#

I need another 16gb of ram, my current PC uses 16gb Tridentz Royale 3200mhz. I'm trying to get something that is compatible with my board and ram. The board is Asus Maximus xi

#

I get too many slowdowns

mellow sigil
#

download code more ram

glass berry
#

Same with unity

#

Unless you just code on paper

latent latch
#

who says you need to run your code

glass berry
dusk apex
fervent furnace
#

you can use mmap to use disk space as additional memory

glass berry
glass berry
modern magnet
#
for (int i = row + rowDirection, j = column + columnDirection; IsWithinBoardBounds(i, j); i+=rowDirection, j+=columnDirection) 
{
    if(IsOccupiedByEnemy(i,j))
    {
        _listOfTilesToHighlightRed.Add((i, j));
    }
    else if(!IsOccupiedByWhite(i, j))
    {
        _listOfTilesToHighlight.Add((i, j));
    }
    else { break; }
    
}

there is one more issue i am facing, i want to exit out of the if loop once the IsOccupiedByEnemy is true, since once it is true, i don't have to check for the enemies behind it since i cannot reach them

sleek bough
#

@glass berry There's no off-topic here

glass berry
fervent furnace
#

then you can break the loop after the first if block

latent latch
#

make use of break; and continue; in your loops

modern magnet
latent latch
#

isn't that what you want

#

if you had multiple loops, one inside another, break; will break out of the current loop.

#

But since this is the only loop then you break; out of this and continue on with your code

modern magnet
#

i dont, in the case that are iterations left where the tiles wherein the checks are left to be made for the white pieces

modern magnet
#

thanks

#

nope actually that wont work i guess

latent latch
#

can always create flags beforehand if you need some for inside of the forloop

#

or inside if you need them for the current iteration

mellow sigil
#

You already have one break inside the loop that works as you want it so I don't see why another one wouldn't do the same

hard viper
#

omg the source code for action is attrocious

#
    public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7,in T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);

    public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
#

for every individual number of arguments, they just defined a separate generic lol

latent latch
#

ah shucks I needed 9 of them

mellow sigil
#

There's no mechanism for variable number of arguments in C# so there's no other way to do it really

latent latch
#

wouldnt params help

#

what does tuple class do

#

probably the same eh

mellow sigil
#

I think everything needs to be the same type if you use params

fervent furnace
#

i remember tuple does the same thing

hard viper
#

ok, so I'm trying to make an equivalent class for big Action delegates, ones with a ton of +=/-=, and balloon to big sizes, by implementing as a list. is there a way to define it as an event, to keep syntax like only exposing += and -= outside the class that does not own it?

fervent furnace
neon plank
#

Question, if I have a from vector and a to vector, how can I check if the closer direction to reach destination is rotating clockwise or counter-clockwise?

hard viper
#

I do not understand

#

maybe describe with points a,b,c

cosmic rain
#

You could use quaternions and unity would automatically rotate it the shortest way

hard viper
#

like, do you have a vector from A to B, and B to C, and need to know how to turn A-B towards A-C?

neon plank
#

My enemies has a forward vector, and my target is in a different direction. Should it rotate clockwise or counterclockise to look at it?

latent latch
#

you've two points which gives a direction, I'm not seeing any rotation here

#

you mean two transforms then

hard viper
#

he has the inverse problem of a rotation matrix

#

he has an in and out vector, and wants to know about the rotation operator that moves in towards out

#

I think

neon plank
# latent latch you mean two transforms then

I have the transform's forwards, and a direction which is (target - enemy).normalized. And I must rotate the first one into the second one, by rotating the enemies in the Y axis

modern magnet
hard viper
#

have you considered using SignedAngle

neon plank
#

Oh, didn't thought.
I may try

cosmic rain
neon plank
#

The only thing I need is actually a float or bool which tells me if I have to rotate clockwise or counter-clockwise from the Y axis, and maybe the rotation intensity. So I don't actually plain to ler or rotate functions

hard viper
#

then just get Mathf.Sign on the SignedAngle

#

Q: I want to make a bunch of ruletiles that have very simple patterns like this, and I think I should be able to do this programmatically. There is a lot of symmetry here, so I'd theoretically only need to uniquely draw: inner corner, inner corner between 2 walls, wall, and open side. But i need to draw a lot of combinations, despite all the symmetry. Is there a smarter way to do this via code?

latent latch
#

prefabs?

hard viper
#

Also, I just tested benchmarking a giant delegate with 100k += operations on it. It is extremely slow, and that scales as n^2. Replacing it with a list implementation makes it way faster. Adding a function to the delegate becomes totally free. And removing a function from delegate is still much faster. The time to fully += 100k, then -= 100k was 10x faster with list implementation

hard viper
abstract portal
#

I need some help... I'm trying to apply "x64" in the checkbox under Standalone->Linux on a native plugin, but when I press "Apply" it goes back to being unchecked. I imported the same plugin into a different project and I can check it no problem. I also double checked that it's compiled for 64 bit platforms... Anyone know what to do?

bright token
#

Hi. Im currently trying to code a Volleyball game in unity. I have done basic movement and also the field setup, (its 2d) but what I dont manage is that I want the player to have to press specific button-combos in order to perform specific volleyball moves. So in this example, I want the player to first click "Q" and then choose one of WASD to choose what side hes gonna set the ball to. This is my code:

private void Setting()
{
    if (Input.GetKeyDown(KeyCode.Q) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
    {
        rb.isKinematic = true;

        if (Input.GetKeyDown(KeyCode.W) && !Input.GetKeyDown(KeyCode.D))
        {
            ballrb.AddForce(transform.up * 30);
            StartCoroutine(Wait());
            rb.isKinematic = false;
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            ballrb.AddForce(transform.right * 30);
            StartCoroutine(Wait());
            rb.isKinematic = false;
        }
        else if (Input.GetKeyDown(KeyCode.W) && Input.GetKeyDown(KeyCode.D))
        {
            ballrb.AddForce(transform.right * 20);
            ballrb.AddForce(transform.up * 20);
            StartCoroutine(Wait());
            rb.isKinematic = false;
        }
    }
}

Right now its the raw version without any timing tries, I didnt manage so I kept it like this. Could someone tell me how to modify it in order to make the player be able to have a little time window (say 1 second) to press the next button?

Thanks!

tawny elkBOT
bright token
#

There you go :)

somber tapir
bright token
somber tapir
#

sure

neon plank
somber tapir
bright token
#

say I want to give them 1 second or 2 seconds to finish that combo

hard viper
#

define a plane with plane normal b. To project A onto B, the projection is proj = (A dot B) * B / (B dot B)

somber tapir
#
float timer;
bool hasPressedQ;
void Update()
{
    timer -= Time.deltaTime;
    if (timer <= 0)
    {
        hasPressedQ = false;
    }
    if (Input.GetKeyDown('Q'))
    {
        timer = 2f;
        hasPressedQ = true;
    }
}``` @bright token
hard viper
#

which is the same as (A dot B.normalized) * B.normalized

#

then A - (A projected onto B) gives A projected onto the plane to which B is normal.

neon plank
hard viper
#

ah, well that would probably do the same thing

#

I mostly work in 2D

#

but you do want to do a projection.

bright token
hard viper
#

if you are projecting onto a trivial plane (like x-y plane), then the projection is trivially (x,y,0)

neon plank
#

Ok, thanks

bright token
#
 private void Setting()
 {
     timer -= time.deltaTime;
     if (timer <= 0)
     {
         setcombo = false;
     }
     if (Input.GetKeyDown(KeyCode.Q))
     {
         timer = 2f;
         rb.isKinematic = true;
         setcombo = true;
     }

     if (setcombo)
     {
         if (Input.GetKeyDown(KeyCode.W) && !Input.GetKeyDown(KeyCode.D) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
         {
             ballrb.AddForce(transform.up * 30);
             rb.isKinematic = false;
         }
         else if (Input.GetKeyDown(KeyCode.D) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
         {
             ballrb.AddForce(transform.right * 30);
             rb.isKinematic = false;
         }
         else if (Input.GetKeyDown(KeyCode.W) && Input.GetKeyDown(KeyCode.D) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
         {
             ballrb.AddForce(transform.right * 20);
             ballrb.AddForce(transform.up * 20);
             rb.isKinematic = false;
         }
     }    
 }

testing now

#

Thank you! I already asked in the c# server and got no answer at all, its been almost 2 hours. You answered quickly and helped me so much

#

it works :)

somber tapir
open charm
#

How do I get a random coordinate from a navmesh

#

So I can spawn enemies in a valid location randomly

polar marten
# open charm How do I get a random coordinate from a navmesh

https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html a random point inside https://docs.unity3d.com/ScriptReference/AI.NavMeshData-sourceBounds.html
this will have biases. there is no general way to select a random point on a navmesh (inside a navmesh) in exactly 1 call that gives uniform likelihood for each point. you can repeatedly sample for small distances until there is a hit for a uniform likelihood, but that may be unexpectedly slow. usually you want enemies to spawn on poisson disks and not uniform random (see image https://repository-images.githubusercontent.com/274968879/4de75d00-c818-11ea-90d9-ba023a3bbe64) this will have a bigger impact on game feel then better random selection

rigid island
#

Ah navmesh data has the bounds, I was looking on NavMesh class

polar marten
#

this will have biases. there is no general way to select a random point on a navmesh (inside a navmesh) in exactly 1 call that gives uniform likelihood for each point

rigid island
#

also depends how far/random it needs to be..

Eg my enemies generally spawn closer to player point so a nice Random.insideUnitsphere works with SamplePosition

upper pilot
#

How would I calculate a % from 0% to 100% based on the input that gets increasingly bigger?
Something like a Tween probably.

For example experience required formula that goes from 10 to 1000, but from level 1 to 10 the total is 100, but 10 to 11 already requires 50 etc. Up to max level of 20(19 to 20 would require like 300xp)

#

What do I need to achieve something similar?
I think Tween might do the trick, but I am not sure.

#

So the total exp from 1 to 20 = 1000, but lower levels require less experience.

rigid island
#

probably a curve

#

or animation curve

upper pilot
#

yeah, what do I need to make it happen?

#

I found something called Weighted Random, so I probably need Weighted not random 😄

#

based on the input

rigid island
# upper pilot yeah, what do I need to make it happen?

ohh thought you wanted this
https://youtu.be/GDcgsJKl7WY

This tutorial will feature use of animaton curves to make a quick visual experience system which can be easily modified and built upon!

Great Related Video (Animation Curves) ► https://www.youtube.com/watch?v=Nc9x0LfvJhI&ab_channel=GameDevGuide
Project Download ► https://github.com/ItsPogle/Leveling-and-Experience-using-Animation-Curves-in-Unit...

▶ Play video
upper pilot
#

no I need like a math behind it

latent latch
#

just use this

upper pilot
#

I am searching for weighted but everything I get is for random numbers lol

#

I'd prefer something I can control myself, dont want to add assets from outside.
I did that once before based on someone recommendation and I regretted it later 😄

#

Also its for random numbers with predefined %, I need something that works with different amount of items.

latent latch
#

actually reading what you're asking I dont think a weighted random would be applicable here

#

what's wrong with a curve again?

upper pilot
#

I don't know what curve to look for

#

Is it a good idea to use animation curve for non animation code?

rigid island
rigid island
upper pilot
#

well there has to be a formula for that curve right?

rigid island
#

why do you need the formula..

upper pilot
#

I thought the video you posted was for animating the progress bar.

latent latch
#

you're just looking to formulate your own experience gain. Usually games do stuff like an exponential curve of some values but it's up to your design

upper pilot
#

ok let me explain it a bit better

rigid island
upper pilot
#

I want to set max exp number, like 10000
This is how much exp you need to reach max level.
max level can be anything, but lets say its 100.

If you go from level 1 to 2, it will use like 0.5%(50) of the 10000
from 99 to 100 it will be like 10%(1000)

somber tapir
# upper pilot I thought the video you posted was for animating the progress bar.

you can do a ticket type system. Every item gets a certain amount of tickets, you put all the tickets in a pot and draw one. Whichever item the ticket belongs to is selected. The more tickets you give an item the higher the chance for it to be selected and you can easily add more items without having to readjust all the values.

upper pilot
rigid island
#

animation curve name is misleading but its just a curve(actually yes sampler is better term because you can make other shape not just curve) .

latent latch
#

your curve would be exp per level

rigid island
#

same thing as typing it manually with as you say, a formula..

fervent furnace
#

animation curve is a sampler

#

just an function(t)

spring creek
rigid island
#

exactly, I use it for movement for example

#

when i want my player to accelerate nicely

upper pilot
#

ah ok so its like Tween, a generic class that can be used eveywhere.
I thought its like Animation based class that has Animation based properties or something.

#

I will check it then.

rigid island
upper pilot
#

Like you said the name is misleading 😄

rigid island
#

agreed

bright token
# somber tapir btw you can check for the Balls y position at the start of your if (setCombo) st...

Ok quickly coming back to you, i advanced a lot and now Im at the part of serving the ball, that one is supposed to be with a real combo of buttons, not like the other one where I pressed "Q" to prepare and then the button in the direction I want it. You said to make a class with a combo list, but I have no clue what that would look like since I just came from 1 year of working on python projects, could you quickly get me in?

rigid island
#

but i assume that was its original usecase ?

#

not sure what unity's thought is there

latent latch
#

if you want exacts then you should just formulate your own function

upper pilot
#

Well you suggested it but then posted a video with animated progress bar so I assumed you got it wrong, cuz it was related to animating a progress bar.

rigid island
upper pilot
chilly parcel
#

what's the proper way to load a uxml document/uss style to create a custom control in c#? For now I'm loading it from resources but I don't like the idea
I mean, using UIToolkit

rigid island
#

i really should learn UIToolkit 😔

chilly parcel
#

I don't like the idea of using the resources folder because I intend to have one single project with multiple scenes that will be build separetelly, if I add everything on resources then they'll always be included in my build

waxen jasper
#

You'd think this would be pretty simple but I need a dang triangle 2D collider. Polygon colliders sinks performance and the object simply doesn't move if I change the polygon settings at all. any solutions?

somber tapir
# bright token Ok quickly coming back to you, i advanced a lot and now Im at the part of servin...
[System.Serializable]
public class InputCombo
{
    public List<KeyCode> keyCodes;
    public Vector2 hitDirection; //The Vector to be applied to the ball if success
}
--------------------------------------------
public class ComboChecker : MonoBehaviour
{
    public List<InputCombo> Combos;
    private List<KeyCode> currentKeyCodes = new();

    public void Update()
    {
        int currentIndex = currentKeyCodes.Count;
        foreach (var inputCombo in Combos)
        {
            KeyCode keyCode = inputCombo.keyCodes[currentIndex];
            if (GetKeyDown(keyCode))
            {
                currentKeyCodes.Add(keyCode);
                return;
            }
        }
    }
}```
This keeps track of any inputs that match one of the combos. 
You can assign the inputCodes in the inspector. It might be better to make that a ScriptableObject for easier editing.
It would probably be better to keep a list of all valid Combos, i.e. if the player pressed Q only check Combos that start with Q and discard the rest until we reset.
bright token
bright token
waxen jasper
maiden junco
#

How can I change the name shown on the inspector of a variable without writing a custom inspector?
Like something like this:

[RenameVariable("Fake name")] public float internalName;

I did it a while a go but don't remember how

bright token
knotty sun
#

Do you mean FormerlySerializedAs ?

maiden junco
waxen jasper
bright token
#

I just pasted the first part into my player script and the 2nd one to a new script

#

i get the error "InputCombo" could not be found

somber tapir
bright token
#

im gonna start a thread if its ok, dont wanna have a conversation only about my problem filling this whole channel :P

somber tapir
# bright token ok ok wait I wanna try to follow

InputCombo is a class that holds a KeyCode list for the combo, i.e. 'Q-W-W' and a Vector2 which will be the force applied to the ball.
ComboChecker has a list of all InputCombos the player can do and a List of KeyCodes that keeps track of which keys have been pressed so far.

hard viper
#

is there a decent workaround to not being able to make static virtual/abstract methods?

#

I have a base class with a static method, where it wants to call a static method, which depends on which class it derives from.

#

....static virtual/abstract isn't allowed. And I would need an instance to call a non-static method

uneven forge
#

Trying to have an action fire only when the right mouse button is released, but these settings don't change anything, it still fires as soon as I rightclick

#

The "Boost" action is a button with no interactions/processors

somber nacelle
#

show where you are getting the input and acting on it

uneven forge
#

in my Player prefab:

somber nacelle
#

well you still haven't shown the Boost method where you're actually acting on that input, but i'd bet you're not doing anything like checking what the phase of the action is. realistically you don't even need that interaction on your input action and can just react to the canceled phase

uneven forge
#

ah my bad, here's the actual method

#

but yeah for every other actions I've been able to just call the method by linking it in the player controller, I don't understand why I suddenly need to do manual checks when there seems to be an option to only fire when releasing the mouse click

somber nacelle
polar jewel
#

Hello, is there a not read-only alternative to Application.persistentDataPath? I try to edit the file after I saving it

somber nacelle
#

the Application.persistentDataPath property is readonly. that doesn't mean the files you write to it are

#

of course the location of the path and how that path works depends entirely on the platform you are building for

polar jewel
#

aah ok that makes sense. Thank you 🙂

somber nacelle
#

this is a code channel. but check the scale

knotty sun
dense void
#

i have no idea why its doing this. Seems to spawn an invisible collider that doesnt exist upon pressing play.

#

i dont have anything in my scripts that would spawn a second collider

rigid island
tawny elkBOT
rigid island
#

also screenshot Inspector for it (player)

dense void
#

capsule

#

player game object

#

nothing else player related has colliders or rigidbodys even when on play

somber nacelle
#

you're mixing a rigidbody and a character controller which is a no-no. also the charactercontroller is a collider

dense void
#

ahhh i knew it was something as simple as that

#

thx

#

I realize that was left on there before from a previous script revision that i forgot to remove

hard viper
#

is there a way to put a class in a namespace without the whole thing being super indented?

rigid island
#

not in c#9

spring creek
rigid island
#

what you want is filescoped namespace

#

only avail in c# 10+ unfortunately

#
namespace Coolness;

class Foo
{
}```
🥲
south gorge
#

Heres my scoreboard

#

Heres my player

#

i cant get the text to update when the player touches the flag

#

right now i get

somber nacelle
#

configure your !IDE

tawny elkBOT
cosmic geode
south gorge
#

now its all looks a little different

south gorge
rigid island
spring creek
orchid gust
#

Hey guys, I currently have code that sets the aim direction for an FOV mesh but does so instantaneously where as I'm looking to Lerp it instead to the target Vector3, would anyone have any good ideas to convert this

hexed pecan
orchid gust
#

I was thinking the same but the issue im having is that Starting angle is a float and Idk if its just not clicking but im having trouble connecting Vector3 Slerp into the float

hexed pecan
orchid gust
#

Its connected to a mesh and is essentially the left most side of it

#

i can grab a hastebin

hexed pecan
#

I'm still unsure how it's supposed to work
But you could just Slerp or RotateTowards from current transform.forward to aimDirection, no?

orchid gust
rigid island
tawny elkBOT
orchid gust
#

oh interesting

orchid gust
#

I think the main Issue Im having is I am calling the SetAimDirection every frame, which isnt quite allowing me to lerp because Im not giving it time to lerp

kindred hearth
#

this is just the part

#

to horizontal movement

#

I put it in update

rigid island
#

it goes in FixedUpdate

#

inputs are read in Update

kindred hearth
#

hmm I'll try

#

thank you

rigid island
kindred hearth
#

I'll rebuild tomorrow its too late rn

kindred hearth
# rigid island it work?

I tried it on the editor and once I put it on fixed update it started working like in the build so it might be have worked already, now I can adjust the values accordingly

#

thank you

rigid island
hard viper
#

let's say I have one component where I need to do a LOT of TryGetComponent calls. Would it be a good idea to speed it up by adding:

public static IReadOnlyDictionary Directory => dict;
private void Awake() { dict[gameObject] = this; }
private void OnDestroy() {dict.Remove(gameObject);}```
Good idea? bad idea?
quartz folio
hard viper
#

that’s my first thought, but it seems like unity would ensure this won’t leak? Given I do need to to a huge amount of TryGetComponent calls for just this one component, what would you recommend?

#

by huge, I am trying to get rid of several thousands of these calls per frame

#

i’m also not a big fan of dumping a ton of memory onto the heap

orchid gust
hard viper
#

maybe I should do a similar thing, but on a singleton holding the dictionary?

quartz folio
#

so unless you're careful you will hold onto those objects in memory for the lifetime of the program

hard viper
#

i’m mostly at the mercy of OnDestroy, which is always kind of wacky

loud wharf
#

And it's not just cause you're using output as the input for lerp.

orchid gust
#

Your right I just switch to Slerp, it doesnt look like it makes an immediate difference but Im sure its my testing enviorment

loud wharf
#

.
I guess, try to imagine a box, and imagine another rod in the middle of the box.
Then imagine the rod rotates. The rate of change depends on the contact point in the rod and the parameters of the square.

#

I'm not sure if I can get the analogy correct. :p

orchid gust
#

yeah, if u get to the corners its gonna change the speed

#

I cant quite explain how to fix the issue i was having so I hope the code can explain itself

loud wharf
#

The right way would have been to get the angle of the aimDirection and the currentDirection and lerp the angles then convert back.

#

In the SetAimDirectionFast, looks like you just set the currentDirection to the aimDirection but did some extra steps converting it into degrees then back into vector.

golden hedge
#

So once I have a system of complicated interlinked scripts, What is a good way to not get lost in it all. I know of flowcharts but are there any alternatives?

#

Or is this the life ive cursed myself too lol

spring creek
golden hedge
#

Hun, Never heard of refactoring. Thanks for the tip, Ima go see what it is

#

Thx dud

queen raft
#

Anyone have problem with jittery movement when timescale is decreased for slowmo? Like everything else is smooth slow mo but the physics stuff moves obviously in large steps.

I've doing movement on fixedupdate and use FixedDeltaTime. Rigidbodies are kinematic and I set their transform position on FixedUpdate. Enabling interpolation does not help.

leaden ice
#

Rigidbody interpolation only works when you're moving via the Rigidbody

#

You are bypassing the physics engine

#

Either use the physics engine to move (with interpolation on) or move in Update

queen raft
hexed pecan
#

Ah yeah, kinematic is probably fine in Update too

flat coral
#

can someone help me fix this error? error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\Jake\My project\Assets\UnityDemoGame\Assets\System.dll' and 'C:\2019.4.11f1\Editor\Data\NetStandard\compat\2.0.0\shims\netfx\System.dll'. Remove one of the duplicate references.
error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\Jake\My project\Assets\UnityDemoGame\System.Core.dll' and 'C:\2019.4.11f1\Editor\Data\NetStandard\compat\2.0.0\shims\netfx\System.Core.dll'. Remove one of the duplicate references.

dusk apex
#

Remove one of the duplicate references

flat coral
knotty sun
flat coral
knotty sun
#

sorry, but I doubt that very much

empty pelican
#

Heya guys, I'm having trouble with this one particular piece of code that's not running for some reason.

#

I don't really know where to begin

swift falcon
#

How do people go about having consoles in their game? Do they write all the available commands in seperate script to process them all or is there a way to put a tag on a function so that they can just call static functions with the params?

#

Consoles usually show available commands when typing so all available commands would need to be listed somewhere to allow filtering

south gorge
spring creek
south gorge
open charm
#

Need some help solving some code

#

the method I am using is very inefficient and is causing a lot of issues rn

#

So I made a script tied to an object that has DontDestroyonLoad but there is a UI button in the scene that has a reference to it. The issue comes when we deload and reload the scene, the UI button would lose all reference to that gameobject and script

#

Im relatively new to unity so ik using singletons and ddols are very inefficient

#

But I do need a solution to fix this

cosmic rain
open charm
#

How do I reassign to an onclick of a button component?

cosmic rain
#

You don't. Which is probably why you should subscribe to events via code. You can invoke a method in a script on the same object from the button. The reference to it won't get lost.

open charm
#

Ive been told to not use singletons for this case since it is very inefficient

cosmic rain
#

And invoke a C# event(Action or custom delegate) from that method.

soft shard
# swift falcon How do people go about having consoles in their game? Do they write all the avai...

Theres a few ways, this may help: https://www.youtube.com/watch?v=VzOEM-4A2OM

Im sure you could setup your own attribute for functions and generate the list with Reflection, what ive done for my game is just made a static class that holds a dictionary of the commands I want, and more-or-less display that dictionary based on how many letters match a key, similar to a "search filter" - if you mean logging Debug.Log messages to a in-game console, theres also this: https://docs.unity3d.com/ScriptReference/Application-logMessageReceived.html

Learn how to create an in-game console that will allow the user to input cheat commands. Perfect for debugging builds and hiding fun easter eggs into your game...

Interior Mapping Shader: https://www.youtube.com/watch?v=dUjNoIxQXAA
UI Line Renderer: https://www.youtube.com/watch?v=--LB7URk60A
Making UI Look Good: https://www.youtube.com/watch?v...

▶ Play video
cosmic rain
open charm
#

thats the instance right?

#

Idk they said my singleton use is very bad

odd furnace
#

I need help configuring visual studio 2022. My code does not autocomplete anymore within visual studio itself and intellisense. Visual studio also does not highlight classes and functions of unity. I have tried to follow all step in IDE Configuration but visual studio still does not work properly

open charm
#

So im alittle worried thats what is causing myy issues

swift falcon
cosmic rain
#

Hard to say anything without seeing your code.

open charm
#

Ye i would share it but there are like 3 different scripts

#

And I dont want to clog up the chat

odd furnace
# odd furnace I need help configuring visual studio 2022. My code does not autocomplete anymor...

I have tried:

  1. Edit > Preferences > External Tools > Select visual studio > External Script Editor > Visual Studio 2022 [17.8.34330]
  2. Checking for updates within the package manager of unity. There are none the current version I have is 2.0.22
  3. Checking for updates within visual studio, there are none. The version shown is [17.8.3].
  4. Installing and reinstalling the game development package within visual studio 2022
  5. I have dotnet version 8.0.0 installed on my computer

I hope this information helps for solving the issue

knotty sun
#

btw not a code problem

odd furnace
knotty sun
#

close vs. in Unity preferences regenerate project files, open vs, screenshot again

odd furnace
knotty sun
#

hmm, still not right, screenshot your External Tools window

odd furnace
knotty sun
#

I meant Preferences->External Tools

odd furnace
knotty sun
#

Select Player Projects and Regen

odd furnace
#

Thanks, visual studio finally works

#

Didn't know it was such an easy fix

knotty sun
#

Really you only need csproj files for embedded packages and player projects, the rest can be turned off

odd furnace
#

Alright I changed it to only those options

#

Now visual studio also looks look way more clean

knotty sun
#

should clean up your solution explorer in VS as well

odd furnace
#

Yeah

spice swift
knotty sun
#

do not ping people into your question

spice swift
#

oops sorry, first time i've used this discord

#

will review the rules

knotty sun
#

anyway sreenshot complete external tools window

spice swift
knotty sun
#

Sorry, VSC, I don't use it

spice swift
#

ok, i'll try download straight VS and see how i go, cheers!

knotty sun
tiny stirrup
#

Is it widely known that unity2D-collision detection for an individual object stops working if you ever directly set transform.position(but directly setting rigidbody2d.position)works perfectly fine, no matter the type of rigidbody)?

I think I understand why it happens(rb pos and trans.pos are not reading the same value and might differ due to simulation and interpolation concerns), but the fact that it seems to break permanently for as long as the object in question is loaded and is never mentioned in any of the documentation has me wondering

in unity 2D, on a what is the intended best practice solution for doing collisions in a game or system that does not intend to use simulated physics(Outside potentially collisions through the physics system)?

cosmic rain
#

If you really want to rebel, you could use physics queries, but imho that's an ugly solution. Might hit the performance as well.

tiny stirrup
#

I guess my intutition is that if you want say basic AABB-collisions in unity, you use boxcollider

knotty sun
#

if you are using physics in any shape or form then you use rigidbodies, if you do not you use transforms

tiny stirrup
#

In unity 3d that is not always true though, there are many situations where as far as I understand it directly setting transform.position even on a simulated object is the 'correct' solution

#

and it certainly never breaks the collisions

#

not to shit on unity2D

knotty sun
#

setting the transform will always break physics

tiny stirrup
#

Break them in the sense that they have to resimulate, yes

#

but not break as in they are now-non functional

cosmic rain
#

No. There's no "resimulation". It breaks different things like collision, interpolation, etc..

cosmic rain
knotty sun
#

it breaks them in the sense that the situation is indeterminate

tiny stirrup
#

youre probably right or were just saying the same thing

#

All Im really trying to ask is: Say I have two squares, and I want unity2D to give me some sort of message or hookable event when they overlap, without having to write custom AABB collisions or whatever, what is the best practice/intended way to do this

#

?=

knotty sun
#

physics triggers

tiny stirrup
#

rb + trigger collider?

knotty sun
#

yes

tiny stirrup
#

huh

cosmic rain
#

Or as I mentioned previously, you can do physics queries every frame(overlap box or something).

cold egret
#
  • Does monobehaviour's invoke method works on local functions?
tiny stirrup
cosmic rain
fervent furnace
#

i think you need to know the name after compilation
ie you need reflection

final geode
#

Hi there!
I am searching for someone who could possibly help me with Unity Render Streaming. I was able to set everything up, I can receive the Audio as well as the Video-Stream in my browser.
Unfortunately I need to send the Microphone input from the browser to the Unity-Application and I am struggling with that. I tried a lot of things with the Audio Stream Receiver and Sender. The Bidirectional Scene is not even showing me options for Microphone or webcam-Input, so I am currently working with the Video-Player-Sample. I would realy appreciate if someone could help me out.

native fable
#

There is a way when importing a package from code via AssetDatabase.ImportPackage(package, false); determine in code which folders will ultimately be imported and appear in the project?
i.e. I did the import and I got these folders, I can somehow get them, so that later I can save them in json and delete them if necessary

hard viper
#

hard coded strings are bad juju

#

you’ll be cursed for using them

steady moat
hard viper
#

i see. wouldn’t that invocation still be pretty slow? because invoke is still searching by string?

#

for reference, this guy is specifically trying to optimize his game because like 10% of all computation time is spent on coroutine and related stuff

fossil goblet
#
    {
        switch (slimeType)
        {
            case SlimeV2.SlimeType.Normal:
                return NormalSprites;
            case SlimeV2.SlimeType.Fire:
                return FireSprites;
            case SlimeV2.SlimeType.Water:
                return WaterSprites;
            default:
                Debug.LogError("Unknown slime type: " + slimeType);
                return normalSprites; // Default to normal sprites
        }
    }```

Anyone know how I could automate this process for all my slimeType enums?
rigid island
fossil goblet
#

as i have a bunch of slimeTypes:

    {
        Normal,
        Fire,
        Water,
        Alien,
        Cat,
        Cyclops,
        Kraken,
        Leaf,
        Shark,
    }```
#

I am probably going to opt to manually add them in everytime i decide to add a new type

knotty sun
craggy veldt
#

that would not solve the issue, or perhaps I misunderstood the question (last post by op)

dusk apex
hexed pecan
#

Coroutines are class objects so they have their small GC overhead too

#

And doing new WaitForX instead of caching it will also produce garbage

fossil goblet
hexed pecan
#

The compiler might turn the switch statement into a dictionary anyway

#

At least that used to be the case with something like 8+ items

#

Dont worry about switch performance, is what Im trying to say

fossil goblet
#

Awesome 🙂

hexed pecan
#

So do what is best organized for you

fossil goblet
#

It's been fun trying to make my game more optimal, ive tried to use more managers that target all my slimes instead of having massive bloat of scripts on each slime

dusk apex
#

If you ever get more than 50, consider populating a list from the inspector and access using enum as int or whatnot.

#

Else a switch is fine for a manageable dataset - relative to size.

fossil goblet
#

i can get around ~200 and it seems runs fairly well on mobile surprisingly

#

no animations yet tho

craggy veldt
dusk apex
#

It's just a lot of copying and pasting. Editing can also be a nightmare that can potentially break stuff

somber tapir
lavish frigate
#

Hey all. I am trying out the new input system and i made a little Vector2 setup with WASD. Im using ctx to store my values in a Vector2, and am moving my player accordingly. Only problem is, once i press a value it never resets to 0,0 when nothing is pressed. Anyone know why?

leaden ice
#

yep

#

you're only subscribing to performed

#

the zeroing out bit happens in cancelled

lavish frigate
#

ahh

leaden ice
#

honestly for every frame movement it's a lot simpler not to use events

#

just use update

lavish frigate
#

if movement.canceled += ctx => movementInput = Vector2.zero?

#

something like that

leaden ice
#
void Update() {
  movementInput = input.CharacterControls.Movement.ReadValue<Vector2>();
}``` that's my recommendation
lavish frigate
#

also, i can normalize my Vector2 either in action or in binding, which is correct practice?

leaden ice
#

there is no correct practice, it depends on your needs

lavish frigate
#

Normalizing in action feels right then, movement works now by the way so thanks again

eager steppe
#

Hey y'all. I've here with a question on optimizing my rhythm game.

Would it be a good idea to pool notes here? I will never be able to anticipate the amount of notes in a map, so I'm unsure if pooling a large amount of gameObjects will work, especially if there is a section of map with an extensive density of notes. I just want to support pooling with maps with just under 10,000 notes (mappers have insane difficulty barriers), and note densities up to 30nps (notes per second)

I currently use Instantiate, but I typically don't find much overhead however I would like to be careful for later.

somber tapir
fervent furnace
#

the node should disappear after player presses it or time out?
return it to pool and reuse the note gameobject

rigid island
#

I love when Unity puts this in their example scripts..

hexed pecan
#

What is not performant

#

I haven't really checked, what kinda overhead does changing material properties have

rigid island
#
void UpdateMaterial()
{
    switch (m_Server.currentIngredientType.Value)
    {
        case IngredientType.Blue:
            m_ColorMesh.material = m_BlueMaterial;
            break;
        case IngredientType.Red:
            m_ColorMesh.material = m_RedMaterial;
            break;
        case IngredientType.Purple:
            m_ColorMesh.material = m_PurpleMaterial;
            break;
    }
}```
#

not sure why they don't just use an event 🤔

hexed pecan
#

I think it's not performant because instead of sharedMaterial it uses material which instantiates a new material IIRC

rigid island
#

just odd doing it every frame when it can just be when m_Server.currentIngredientType.Value changed

#

they literally have an event for that xD

#

wish they wrote in comment why they did it that way..just laziness or wat..

eager steppe
fervent furnace
#

the pool should grow dynamically if you need more objects

native fable
#

AssetDatabase.onImportPackageItemsCompleted

I use this callback when execute AssetDatabase.ImportPackage(package, false);

everything works well for simple packages, but when I tried to import the FacebookSDK or Firebase package, for some reason this event simply does not get called... Can someone tell me why this is happening?

somber tapir
boreal condor
#

Hey there, I wanted to ask if it is possible to draw a prefab or something using either gizmos or similar techniques, i need to preview some motion that needs to be accurate displaying a referenced gameobject

#

I have tried instantiating during gizmos but I do not know if it's possible to know when an object has been deselected in order for the prefab to disappear and prevent clones, and keeping the hierarchy clean

native fable
#

Good evening everyone

Auto-importing packages from code

I ran into a small problem that is a little annoying

This means I import packages through code like this

AssetDatabase.ImportPackage(package, false);

Unity has the following events

AssetDatabase.onImportPackageItemsCompleted += OnImportPackageItemsCompleted;

AssetDatabase.importPackageStarted += name => Debug.Log($"importPackageStarted : {name}");

AssetDatabase.importPackageCancelled += name => Debug.Log($"importPackageCancelled : {name}");

AssetDatabase.importPackageCompleted += name => Debug.Log($"importPackageCompleted : {name}");

AssetDatabase.importPackageFailed += (name, message) => Debug.Log($"importPackageFailed : name: {name} message : {message}");

The crux of the problem is this

If I import some simple packages with several files, then everything works as expected for callbacks, they are called as in the screenshot (screen 1)

But if I take some package from Facebook or Firebase, then the callbacks are like this, and the Complete callback is not called at all (screen 2)

Does anyone have an idea why this could be?

polar marten
boreal condor
#

but well if there's no other choice i'll do that

polar marten
#

if you want to visualize in the scene view

hexed pecan
#

And then draw the child meshes with their localPosition and localRotation

#

Might be more complex if your children are nested

#

In any case set the matrix and then draw them with positions/rotations/scales relative to the parent

ornate hare
#

!code

tawny elkBOT
cerulean mist
#

Hey all! Just wanted to ask a quick question in here -- i'm currently working with Editor scripting in Unity for the first time and working on making a better effects system for my game.

The way it works is you can add multiple effects to the list of abstract EffectAction classes. You can add actions like camera shake, playing audio, spawning a particle, etc. For every effect I want to add, I have to add the effect into an enum and use a switch to add the coressponding effect to the list --- which is fine right now but I feel it may get tedious as I continue to add effects. Is there a better way of doing this?

Here's the editor code:

#if UNITY_EDITOR
[CustomEditor(typeof(EffectEvent))]
[CanEditMultipleObjects]
public class EffectEventEditor : Editor
{
    public Events eventSelected;
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        EditorGUILayout.LabelField("Actions:");
        eventSelected = (Events)EditorGUILayout.EnumPopup(eventSelected);

        string buttonName = $"Create Action";
        if (GUILayout.Button(buttonName))
        {
            switch(eventSelected)
            {
                case Events.CameraShake:
                    (serializedObject.targetObject as EffectEvent).AddAction(new CameraShakeAction());
                    break;
                case Events.PlayAudio:
                    (serializedObject.targetObject as EffectEvent).AddAction(new PlayAudioAction());
                    break;
            }
        }
    }

    public enum Events
    {
        CameraShake,
        PlayAudio,
        SpawnParticle
    }
}
#endif```
pure garden
#

Any idea if there is any way that the clients that are not hosts of a lobby receive callbacks from LobbyEventCallbacks ?
at the moment only the host receives them

(using the lobby service)

// THIS IS ONLY CALLED ONCE AT THE START OF THE SCRIPT

LobbyEventCallbacks _callbacks = new LobbyEventCallbacks();
ILobbyEvents _lobbyEvents;

private async void SubscribeToCalls()
    {
        //SUBSCRIBE TO CALL
        _callbacks.LobbyChanged += Callbacks_LobbyChanged;

        try
        {
            _lobbyEvents = await Lobbies.Instance.SubscribeToLobbyEventsAsync(curLobby.Id, _callbacks);
        }
        catch (LobbyServiceException e)
        {
            Debug.Log(e);
        }
    }
    private void Callbacks_LobbyChanged(ILobbyChanges changes)
    {
        Debug.Log("Lobby Changed");
        //ONLY THE HOST RECEIVES THIS MESSAGE
    }
}
sharp bison
#

I have a problem with managing my code, I'm making a system where you pick up a object, the placement trigger is activated and when you drop the object in it it activates another object and it destroys those two. Now I'm wondering how i could do this to multiple object and multiple placement triggers in 1 script or maybe if you have another solution i would be happy if you said it. Here are the scripts:

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

public class PickUpScript : MonoBehaviour
{
    [SerializeField] private LayerMask PickupMask;
    [SerializeField] private Camera PlayerCam;
    [SerializeField] private Transform PickupTarget;
    [Space]
    [SerializeField] private float PickupRange;
    private Rigidbody CurrentObject;
    private bool isHoldingObject = false;
    public GameObject Placement;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (isHoldingObject)
            {
                DropObject();
            }
            else
            {
                TryPickUpObject();
                Placement.SetActive(true);

            }
        }
    }

    void TryPickUpObject()
    {
        if (CurrentObject == null)
        {
            Ray CameraRay = PlayerCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
            if (Physics.Raycast(CameraRay, out RaycastHit HitInfo, PickupRange, PickupMask))
            {
                CurrentObject = HitInfo.rigidbody;
                if (CurrentObject != null)
                {
                    CurrentObject.useGravity = false;
                    isHoldingObject = true;
                    CurrentObject.isKinematic = true; // Prevent physics from affecting the object
                    CurrentObject.transform.SetParent(PickupTarget); // Set object's parent to the PickupTarget
                    CurrentObject.transform.localPosition = Vector3.zero; // Set local position to center within the target
                    CurrentObject.transform.localRotation = Quaternion.identity; // Reset local rotation
                }
            }
        }
    }
#

I removed the drop logic because it was irrelevant and i couldnt send the message

#
using UnityEngine;

public class PlacementTrigger : MonoBehaviour
{
    public GameObject objectToActivate; // Assign the GameObject to activate in the Inspector

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Item"))
        {
            // Activate the assigned object
            if (objectToActivate != null)
            {
                objectToActivate.SetActive(true);
            }

            // Destroy the collided item and the trigger
            Destroy(other.gameObject);
            Destroy(gameObject);
        }
    }
}
#

I would gladly hear what you have to say

fervent furnace
#

i think you need array

#

or queue, though i suggest using array since it is serializable in inspector
when you pick up an object, it needs to search for the corresponding collider to activate
when the collider is triggered, it needs to activate next object

#

then overlapXXX should work for checking if the drop position is inside the triggered collider

sharp bison
#

I get the idea but im not going to lie im not very experienced with coding, i understand most of the code but i cant really code a lot myself (i used chatgpt for the code lol), i didnt want to post this in the beginner code channel since this is pretty advanced i think

#

how do you even get that smart

#

ive actually been using unity for like 3 years and i havent learned a lot of coding

#

i guess im going to research what you said to me, thanks for the help

pure garden
#

You have an object that you place in a trigger and when that trigger detects collision you set an object to active?

sharp bison
#

because all of them will be masked under item and tagged item

pure garden
#

oh ok yh understood

sharp bison
pure garden
#

Just add a variable to placement trigger of type gameobject and check if other.gameobject is equal to desired object

#

ig?

sharp bison
sharp bison
pure garden
#

Do a List of gameobjects and check if the List contains other.gameobject

sharp bison
#

Okay let me make an example

#

Theres a ornament on the floor

#

i pick it up

#

the placement trigger object activates