#archived-code-general

1 messages · Page 238 of 1

swift ocean
#

could be that the object get destroyed before it get split

near sail
#

that il forget about within a few weeks lol

#

because I saw one online but the person who uploaded it to YT didnt provide a link to play it

strange stone
rigid island
#

mesh manipulation is indeed not a beginner topic @near sail

near sail
#

aww rip

rigid island
#

you should probably learn how to make an actual mesh before destroying one or cutting one..

#

look him up

near sail
#

il take a look

#

ty

boreal condor
#

got a question, i am trying to turn a vector3 from world space to be mirrored on a canvas UI in overlay mode, using the search engines give me terrible results, How is this process called and/or how can I achieve it?

#

i basically want to render an image on top of an object and make the image follow it

swift ocean
#

there a many different types of mesh

latent latch
#

Viewing frustum to Screen Coordinates?

swift ocean
#

Vector3 = 3D space, Vector2 = 2D space

spring creek
# swift ocean you mean turn it to Vector2?

they just mean convert from the worldspace coordinate system (with the center of the world as 0,0,0 and going positive and negative) to screenspace coordinates (with 0,0 on the bottom left and going only positive up to the resolution values)

boreal condor
swift ocean
#

you can also find the code for Vector2 in ChatGPT or online code libraries like github or stackflow etc

spring creek
swift ocean
#

based on your use

#

code varies signaficantly, use library or chatbots for help based on what you need

boreal condor
swift ocean
latent latch
#

Ah, right it's on the camera. I was looking to see if transform method had it

swift ocean
#

wait

#

i miss read

latent latch
#

or matrix4x4

boreal condor
#

will look into this later

swift ocean
#

i recommend you to open a new test project and implement that specific function

#

so you can test freely

latent latch
#

it does it through the viewing frustum because it's just a point so that makes sense

#

otherwise you'd need a transform

#

Actually you could just do it with the camera matrix and make a matrix4x3 with the point

#

I forget

boreal condor
#

i have an array of objects and i want them to have images on top lol

#

i just dont know how the effect is called

#

generally used to tell you to pick up an object and stuff like that

#

i'll see what i can do with that function, thanks

latent latch
#

Aethenosity is on the money on what to do so read into that method

polar marten
boreal condor
#

yes

polar marten
#

i will be honest, this is shockingly complicated in Unity, because of UGUI

#

not because of the math

boreal condor
#

guess i'll have to search in older projects, i had a function that did this but can't find anything that explains it tho

boreal condor
#

not sure what it is, it just uses the screen size

polar marten
# boreal condor not sure what it is, it just uses the screen size

anyway, use this https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html

set the localPosition of the rectTransform to ( the screen point to the local point in the recttransform's parent), multiplied by the canvas scale factor

#

it's hard

boreal condor
#

what

#

that returns boolean

#

ah i understood

swift ocean
#

strange that i have Time delta time yet my mouse movement get slower with increased frame rate

leaden ice
#

It's already framerate independent

swift ocean
#

ahhhh

#

thanks

#

i was dying inside

#

it worked

boreal condor
#

okay learned something new, thanks guys

vagrant lake
#

When i press play my camera is being teleported away from the player, how could i fix this?

#

i also get a ton of these errors even though Mouse X is setup

rigid island
vagrant lake
#

oh

#

so what does the error want from me then?

rigid island
#

it's telling you MouseX isn't a thing

spring creek
rigid island
#

perhaps it wanted you to look inside Input class for the proper name 🙂

vagrant lake
#

ok i fixed that so there are no more error messages and i can use my camera, but it still teleports away from the player on start

rigid island
#

as for the camera problem, hard to know without knowing more about the scripts

#

or how is it that camera is moving in the first place

vagrant lake
#

heres the scripts themselves

spring creek
rigid island
#

again you should not multiply your mouse by Time.deltaTime

#

did mention this b4

vagrant lake
#

my bad, i forgot about that bit

#

sorry

rigid island
#

i would just put camera holder as child of player

#

only rotate player to rotate camera on Y

vagrant lake
#

ok

rigid island
#

try to keep it on Pivot mode, not Center
Sometimes it throws you off for precision

rocky basalt
#

I naïvely thought I could make an AssetReference field on a class, then use that field to directly reference an AudioClip I had dragged into that field.

But I'm getting an error in the IDE *Cannot implicitly convert type 'UnityEngine.AddressableAssets.AssetReference' to 'UnityEngine.AudioClip' *

Anyone know a quick/easy way to achieve my objective using AssetReference (or other easy method). Thanks!

somber nacelle
#

Anyone know a quick/easy way to achieve my objective using AssetReference (or other easy method)
what is your objective?

rocky basalt
#

Eh now I kinda regret asking this lol. Because I guess I could just use an AudioClip reference directly on my SO. I can't remember why I thought AssetReference was the way to go anymore.

Basically I wanna make a list of all my built-in audio assets along with a unique ID to reference them by.

So I made a SO that has a field for AudioClip and a unique GUID string.

blazing smelt
#
if (g != null && g.garmentObject)
{
    Destroy(g.garmentObject);
}

if g.garmentObject is a class rather than a bool, what does referencing it this way mean in the context of an if statement?

dusk apex
#

Normally it'd be an implicit null check

blazing smelt
#

im snooping out a big-ass error that causes the entire editor to crash, so I'm stamping out any possible dodgy code

dusk apex
dusk apex
dusk apex
#

A good way to see if this is an factor is to comment out the destroy call

blazing smelt
#

but I want to make sure I know exactly what the above code could be doing

blazing smelt
#

but the code is such a mess that I want to make sure if this might be contributing to some other kind of error

dusk apex
#

The break point would simply occur before the crash. Did you step through to the very line before the crash?

blazing smelt
#

I didn't make it and it's both very complicated and very poorly documented

blazing smelt
#

i think that the code might occur in an OnDestroy() function on a script that happens to be on the object being destroyed

dusk apex
#

Comment out Destroy and see if any crashes are occurring

#

You can substitute with inactive objects temporarily for the test if those objects need to be removed from the game

vagrant lake
#

does someone know why my player is being slippery when moving? i tried increasing my drag but that didnt do anything

#

sorry if im just being stupid lol

spring creek
vagrant lake
#

five

#

then i tried 100 but still nothing

foggy cipher
#

What's wrong here?

    void OnDisable()
    {
        Mesh mesh = ((MeshFilter)gameObject.GetComponent("MeshFilter")).mesh;
        string out = "";
        foreach (Vector3 vertex in mesh.vertices)
        {
            out += "v " + vertex.x + " " + vertex.y + " " + vertex.z + "\n";
        }
        for (int i = 0; i < mesh.triangles.length(); i++)
        {
            out += "f " + mesh.triangles[i] + " " + mesh.triangles[i+1] + " " + mesh.triangles[i+2] + "\n";
        }
        
        print(out);
    }
spring creek
tawny elkBOT
rigid island
#

also don't use out as variable name

#

its a reserved keyword

vagrant lake
spring creek
tawny elkBOT
vagrant lake
#

FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial

In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.

If this tutorial has helped you in any way, I would really appreciate...

▶ Play video
spring creek
vagrant lake
#

ok

foggy cipher
# spring creek Show the whole script !code

that was basically the whole script

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

public class geoExporter : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void OnDisable()
    {
        Mesh mesh = ((MeshFilter)gameObject.GetComponent("MeshFilter")).mesh;
        string out = "";
        foreach (Vector3 vertex in mesh.vertices)
        {
            out += "v " + vertex.x + " " + vertex.y + " " + vertex.z + "\n";
        }
        for (int i = 0; i < mesh.triangles.length(); i++)
        {
            out += "f " + mesh.triangles[i] + " " + mesh.triangles[i+1] + " " + mesh.triangles[i+2] + "\n";
        }
        
        print(out);
    }
}
fervent furnace
#

out is reserved keyword as navarone says
and getcomponent can take a generic parameter, also consider using string builder

quartz folio
#

also, do not call mesh.triangles inside of a for loop

foggy cipher
#

good point

quartz folio
#

cache it to an array before using it anywhere in the for loop or else it will repeatedly reallocate an entire array every time it's called

foggy cipher
#

well, looks like I crashed unity

spring creek
#

Oh

foggy cipher
#

huh, turns out unity doesn't like it when you print a crazy ammount of text at the end of runtime, whoda thought

#

well, maybe unity just doesn't like me

cosmic rain
foggy cipher
#

well my end goal is to export it to a .obj file

cosmic rain
#

If you gonna do it, it should probably not be in OnDisable

quartz folio
#

I'd also note that you're iterating the triangle array incorrectly, it should be +=3

foggy cipher
#

yeah, it executes on the 30th frame now

quartz folio
#

so you currently have 2x the amount of triangles listed

foggy cipher
#

ah yes

#

now how do I write to a file with unity?

quartz folio
#

Same way as in C# generally

foggy cipher
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class geoExporter : MonoBehaviour
{
    int frame = 0;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void LateUpdate()
    {   
        if (frame == 30){
            Mesh mesh = ((MeshFilter)gameObject.GetComponent("MeshFilter")).mesh;
            
            using (StreamWriter outputFile = new StreamWriter("output.obj"))
            {
                Vector3[] vertices = mesh.vertices;
                foreach (Vector3 vertex in vertices)
                {
                    outputFile.WriteLine("v " + vertex.x + " " + vertex.y + " " + vertex.z);
                }
                int[] triangles = mesh.triangles;
                for (int i = 0; i < triangles.Length; i+=3)
                {
                    outputFile.WriteLine("f " + triangles[i] + " " + triangles[i+1] + " " + triangles[i+2]);
                }
                print(vertices.Length);
                print(triangles.Length);
            }
        }
        frame ++;
    }
}

this makes a file correctly, but its all zeros

cosmic rain
#

Use the debugger to step through the code

foggy cipher
#

also how is it possible that the number of vertices is equal to the number of triangles?

leaden ice
#

You could have more triangles than vertices, more vertices than triangles, or an equal number of each

foggy cipher
#

yes, but it's incredibly unlikely for them to be equal (I'm doing marching cubes)

leaden ice
#

triangles.Length is actually 3X the number of triangles

foggy cipher
#

ah

#

ofc

leaden ice
#

if you never reuse any vertices

#

and every vertex is used in a triangle

#

you'll have exactly that 3:1 ratio of vertices to triangles

#

and triangles.Length == vertices.Length will be true

foggy cipher
#

now I just have to figure out how I have 393216 vertices, with all of them displaying just fine, yet the triangle and vertex lists are filled with zeros

#

well, it isn't zeros, but it's not better lol

next sparrow
#

Hello, I'm having an issue with bullet trails. The bullet gets destroyed when it hits something obviously and there is a trail attached to the bullet. The bullet uses a rigidbody. I also keep the trail alive after its parent, the bullet, gets destroyed (by simply unparenting it). My issue is that if the bullet hits something right in front of the shooter, the trail does not appear. If the target is far away, the trail appears correctly. I'm not sure how it works, but I'm guessing the bullet gets destroyed before the trail can even start? The bullet has a speed of 200 which makes it quite fast. How could I fix that?

foggy cipher
next sparrow
ember gate
#

Help, I don't understand this error. Anyone seen it before and can help?

quartz folio
#

Can't tell you anything more without the stack trace or code

ember gate
#

ok @quartz folio I'll dm u the code

quartz folio
#

No

#

!code

tawny elkBOT
ember gate
#

oh sorry

#

do you not want me to dm?

#
if (EnemyList.Count > 0)
        {
            DistanceXandY(gameObject.transform.position.x, gameObject.transform.position.y, EnemyList[0].Troop.transform.position.x, EnemyList[0].Troop.transform.position.y);
            distanceClosest = distance;
            distanceDirectClosest = DistanceDirect(distanceClosest);

            foreach (EnemyTypes enemy in EnemyList)
            {
                DistanceXandY(gameObject.transform.position.x, gameObject.transform.position.y, enemy.Troop.transform.position.x, enemy.Troop.transform.position.y);

                distanceDirectCompare = DistanceDirect(distance);

                //If out of checked so far closest is further than new one, then get that enemy
                if (distanceDirectClosest > distanceDirectCompare)
                {

                    closestEnemyNumber = enemyNumber;


                }

                enemyNumber++;
            }
            closestEnemy = EnemyList[closestEnemyNumber];

            ratioX = 1 / ((distanceClosest.x + distanceClosest.y) / distanceClosest.x); //5, 10 ratio : 15/5 = 3
            ratioY = 1 / ((distanceClosest.x + distanceClosest.y) / distanceClosest.y);

            if (hasUpdateBeenCalled == false)
            {
                velocity = new Vector2(ratioX * 100, ratioY * 100);
                //velocity = new Vector2(0, -10);
                hasUpdateBeenCalled = true;
            }

            /*
            shootAngle = Mathf.Asin(closestEnemy.Troop.transform.position.y / closestEnemy.Troop.transform.position.x);
            myVector = Quaternion.Euler(0f, 0f, shootAngle) * myVector;

            gameObject.transform.Rotate(0,0, myVector);
            */
        }
    }
quartz folio
#

Presumably closestEnemyNumber is out of range of the list when you do EnemyList[closestEnemyNumber]

ember gate
#

yeah very sorry

quartz folio
weak venture
#

So I have 2 goals around my player 2d colliders... feet need to have actual friction for movement to feel correct and body needs low friction maybe even a small amount of bounce to prevent air movement from allowing players to push themselves against walls.
My initial soln was to have two colliders covering the relevant space with different physics materials but I think thats causing relability issues in my other collision response components where a quick enter/exit or a multi enter/exit from these multiple colliders is breaking the assumptions.
So I could harden all my trigger reaction stuff against this but I'm wondering if people here might be have a suggestion for some other soln to the original problem that would let me keep trigger reactions dead-simple

azure dome
#

What is the best way to replace a sprite sheet with a new one? Because when I do that I have to setup all item sprites again after adding one icon. Is there a way to do this without setting up sprites again?

vagrant lake
#

what is this thing that moves my player when i move it?

cosmic rain
vagrant lake
#

In the middle-right of the screen

#

The empty game object

cosmic rain
#

The transform gizmos?

#

That's your player

vagrant lake
#

How come it’s not like On my player

cosmic rain
#

You can see in the inspector and the hierarchy

vagrant lake
#

Oh I thought they were 2 separate things

cosmic rain
cosmic rain
vagrant lake
raven vault
#

So im getting this error, i dont know what its referring to at all, any help?

The first one, the other two wouldnt exist without the first one

knotty sun
raven vault
#

so i cant fix this? not even completely reinstalling anything or anything

knotty sun
#

nope, just clear the console and they should go away

raven vault
#

yea, but it fails my upload for the game because of the error

knotty sun
#

you mean your build?

raven vault
#

yea, it wont work with that error there

knotty sun
#

That looks like it is Editor only code so should not even be in a build. You might be better asking in the VRC server

raven vault
#

yeah, im trying there too, its just that this error is so unique compared to my other errors that i dont know exactly what is causing it

stark elk
#

I've created a bootstrap scene for my game to manage the order of initializations for singletons, etc.
Can anyone recommend a workflow/workaround for this approach to load this stuff first when running an arbitrary scene in the editor?

knotty sun
#

Do you have an Editor window open which has anything to do with VRC?

raven vault
#

nothing other than the sdk's splash screen.

knotty sun
#

screenshot

raven vault
knotty sun
#

Do you not read what is on your screen?

raven vault
#

ive tried that already......same error

#

error is there still

#

not the "getting the control...." but same, this is a vrc error at this point so im jumping servers.......

knotty sun
#

totally different problem

#

try installing the version suggested by the first warning

lean sail
knotty sun
stark elk
storm tulip
#

Does anyone know if there's a builtin Decompose method for float4x4? i.e. one that extracts the translation rotation and scale

cold parrot
royal temple
#

Hello everyone;
My project's artist has come up with a clever way to save time for himself by having material variants have different parent declinations.
We tried having a simple scrit that reparents a one single Material used by every characters and this only works in Editor because you can't change parent property in a Release Build.

I'm not too familiar with this pipeline and materials, is this somehing that can be done, or are we approaching the problem the wrong way please? Thanks

latent latch
#

Usually if you're modifying materials at runtime you're creating a new material instance. Lot of the variant batching is at compile time for what I've read and it does kinda make sense, but I've not read too much into it.

#

It probably creates its own additional source code for variants is my assumptions

forest linden
#

Trying to use visual scripting for enemy AI logic by using it as a flowchart to control which voids to use in my actual script.

How do I get it to use public voids from a C# script

*I know there is a specific server for visual scripting but I'm not getting a response

latent latch
#

Methods? I don't use VScripting but it seems like you're looking at a different script of attributes there.

forest linden
#

no, its the same script

latent latch
#

I could only suggest looking how a method(?) like Set Attacking is configured, otherwise may be wise to try out some tutorials since is probably very basic enough to find that info

royal temple
knotty sun
royal temple
#

I'm wondering if this can work with MaterialPropertyBlock 🤔

native fable
#

Hello

I’m making a system of requirements for a gun (required reload time, required damage, required gun magazine size)

More experienced ones, please tell me how to do this adequately, so that I have all the requirements stored, in principle, in one list, how to organize an adequate abstraction, because now I can’t come up adequately and it turns out that I can come up with the maximum on the screen

that is, I would like to conveniently get the parameter I need by type to compare the required type

if the type requested type.MagazineSize then it would pull int, and if reloadTime then float

the essence is the following

there is a service from which I can get the current gun stats

and there are requirements to pass the level

I need to compare them and update my UI

stoic ledge
#

How can I launch a dedicated server build from MacOS terminal

Can't even launch it, "open executableFileName" doesn't work.
The executable is correct, double clicking it works.
Need to launch it with arguments.

dense swan
#

excuse me, I heard there is a better way to do this:
if (rigRadio != null) rigRadio.SetRigStatus(false);

What is it?
running a function only if the object is not null. without using if (something!=null)

sturdy igloo
#

I have a question reguarding the reading and writing of data to mass amounts of gameobjects:

In my scene, I have 1024 total tiles (these are gameobjects instantiated by a script that just loops over the X and Y axis), lets say I want a tile with ID 7 to have a set amount of stone, but tile ID 8 should have a set amount of oil, and so on so forth.

What would be the proper way to do this without much overhead?

Say if there was an extraction building, that had to collect the stone from the tile, how could it read the data from said tile?

fervent furnace
#

you should have a eg tile manager, then ask the manager to return that tile for you

leaden ice
slate trellis
#

Quick question. My editor (VS Code) grays out something and tells me "Name can be simplified". Will that pose any problems, or is it a suggestion on how to make my code cleaner? Relevant Snippets:

leaden ice
#

The type can be implied from your parameter

#

Same for when you call your custom function

somber nacelle
#

the only problem here would potentially be from that result is not null which might return true if the component you are getting has actually been destroyed and is therefore == null but not really null

slate trellis
#

that was actually your code @leaden ice

somber nacelle
leaden ice
#

But in your first screenshot you can remove the <StatsHandler>

#

It's not my code that can be simplified but yours 😜

slate trellis
leaden ice
#

Oh

slate trellis
leaden ice
#

Uhhhhh ok back to delirium

somber nacelle
slate trellis
#

if that's what you meant

somber nacelle
#

you've removed the out parameter, that is required

slate trellis
somber nacelle
#

you need the whole parameter. is it just the generic type parameter (<StatsHandler>) that can be removed

slate trellis
somber nacelle
#

show it

#

that is what i asked for

#

also !screenshot

#

!screenshots

tawny elkBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

slate trellis
#

nvm, I found what I goofed:

// goof
if (collider.gameObject.TryGetComponentInParent<>(out enemyStats))
// fix
if (collider.gameObject.TryGetComponentInParent(out enemyStats))```
slate trellis
somber nacelle
#

screenshots make it more difficult for everyone helping you though. especially those first couple where discord only shows part of them so it can shove them all inline in the same message

slate trellis
#

yeah, makes sense now in hindsight. I just wanted to show the message mostly

#

now it's fixed. Although would there be a problem if I didn't remove the <StatsHandler> part?

somber nacelle
#

nope, the compiler just infers it from the type of variable you pass as the out param so its just more verbose with it included

slate trellis
#

ah gotcha. That was my question mostly

#

thanks again, and sorry for the trouble.

modern magnet
#

hey everyone, I want some help with an issue that I have been facing while making a chess game, the chess board is made up of a rows array, the rows array is a game object array, and the pieces are not a child of the chess board object but child of a different object, now i do not know how do i ensure that when a piece is selected it highlights the legal spaces that it can move to, such that a piece which is already occupying a space, this space shouldn't get highlighted

somber nacelle
#

ideally your array should contain the type that you actually care about rather than just GameObject. but you would just check your array when determining what are legal spaces and if a piece occupies that space in the array then you know it isn't a legal move

modern magnet
#

umm i am a bit confused here

modern magnet
somber nacelle
#

the one containing your pieces

modern magnet
#

ahh, no, currently there is no array that stores the pieces, all the pieces are just child of a game object

#

this is want i meant

somber nacelle
#

ideally your array should contain the type that you actually care about rather than just GameObject
as in, make an array for your pieces

#

the array represents spaces on the board. you put pieces in the index that represents their current position on the board

modern magnet
#

here is the chessboard, the Row child are rows of the chessboard and their child are tiles of a chess board

lunar acorn
#

Is there a clear and concise place to see how Unity Lobby events work? The documentation and Youtube videos ive found barely help at all.

For instance, how do i actually access the data in this:

swift falcon
#

Hey i need help

#

!code

tawny elkBOT
vagrant agate
vagrant agate
swift falcon
swift falcon
swift falcon
#

The problem is when the player restart the game the variables get missing

#

Let me change it

#
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using TMPro;

public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    public GameObject gameOverUI;
    public TextMeshProUGUI restartCountdownText;
    public PlayerShooting playerShot;
    public FPSController fpsController;
    public PauseController pause;

    private float initialCountdownTime = 10f; 
    private float currentCountdownTime; 

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }

    private void Start()
    {
     
    }

    public void GameOver()
    {
        gameOverUI.SetActive(true);
        Time.timeScale = 0;
        playerShot.enabled = false;
        Cursor.visible = true;
        pause.enabled = false;

       
        if (fpsController != null)
        {
            fpsController.enabled = false;
        }

        currentCountdownTime = initialCountdownTime;
        StartCoroutine(RestartCountdown());
    }

    private IEnumerator RestartCountdown()
    {
        while (currentCountdownTime > 0)
        {
            restartCountdownText.text = Mathf.CeilToInt(currentCountdownTime).ToString();
           

            yield return null;

            
            currentCountdownTime -= Time.deltaTime;

          
            if (Input.GetKeyDown(KeyCode.Space))
            {
                currentCountdownTime -= 1;
            }
        }

        
        RestartGame();
    }

    public void RestartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        Time.timeScale = 1;
        playerShot.enabled = true; 
        Cursor.visible = false;
        pause.enabled = true;

       
        if (fpsController != null)
        {
            fpsController.enabled = true;
        }

        
        restartCountdownText.text = "";
    }
}
somber nacelle
spiral ibex
#

Hey 👋 Updating our project from unity 2021 to 2022 made it so one folder specifically is suddenly not compiled within the project. Any references to its contents throw a compilation error. Anyone encounter anything similar?

swift falcon
modern magnet
leaden ice
#

What folder is it?

next sparrow
#

Hello everybody, I'm having issue with creating a bullet pool.

#

Here is a show case of the problem

#

And here is when I enable pooling. It seems like the data of the pooled reused bullets are not correctly overwritten

#

Here is the code from my rifle spawning the bullet:


    public void Shoot(RaycastHit hit)
    {
        //Preventing shooting while weapon on cooldown
        if (cooldown > 0) return;

        Vector3 aimDir = (hit.point - bulletSpawner.position).normalized;
        BulletProjectile bp;
        if (Weapons.instance.bulletsInPools[bulletPoolIndex].Count > 0 && Weapons.usePooling)
        {
            bp = Weapons.instance.bulletsInPools[bulletPoolIndex][0];
            Weapons.instance.bulletsInPools[bulletPoolIndex].RemoveAt(0);
        }
        else
        {
            bp = Instantiate(bullet, bulletSpawner.position, Quaternion.identity);
            bp.name = owner.weapon.name + " Bullet " + Weapons.bulletIndex;
            Weapons.bulletIndex++;
        }
        bp.Setup(owner, bulletSpawner.position, bulletSpawner.position + aimDir * range, aimDir, speed, bulletPoolIndex);
        cooldown = Time.time + 1 / fireRate;
        //Debug.Break();
    }
#

And here is the bullet code:

    public void Setup(PlayerController player, Vector3 start, Vector3 end, Vector3 aimDir, float speed, int bulletPoolIndex)
    {
        gameObject.SetActive(true);
        bullet.SetActive(true);
        this.bulletPoolIndex = bulletPoolIndex;
        owner = player;
        startPosition = start;
        transform.parent = null;
        transform.SetPositionAndRotation(start, Quaternion.LookRotation(aimDir, Vector3.up));
        targetPosition = end;
        float distance = Vector3.Distance(startPosition, targetPosition);
        float timeAlive = distance / speed;
        timeToDie = Time.time + timeAlive;
        rb.AddForce(aimDir * speed, ForceMode.VelocityChange);
        TeamColor();
    }

    private void Update()
    {
        if (timeToDie <= Time.time)
            Explode(false, Hits.Ground);
    }

    private void Explode(bool hitSomething, Hits hit)
    {
        if (hitSomething || explodeOnNoHit)
        {
            ParticleSystem prefab = groundHit;
            if (hit == Hits.Soldier)
                prefab = playerHit;
            ParticleSystem ps = Instantiate(prefab, transform.position, Quaternion.identity);

            //Change color to team color
            if (hit == Hits.Soldier)
            { 
                ParticleSystem.MainModule psm = ps.main;
                psm.startColor = Config.TeamColor(owner.Team);
            }

            ps.transform.LookAt(startPosition);
        }
        rb.velocity = Vector3.zero;
        bullet.SetActive(false);
        Invoke(nameof(Pooling), trail.time);
    }

    private void Pooling()
    {
        if (Weapons.usePooling)
        {
            transform.parent = Weapons.instance.bulletPools[bulletPoolIndex];
            Weapons.instance.bulletsInPools[bulletPoolIndex].Add(this);
            gameObject.SetActive(false);
            //Debug.Break();
        }
        else
        {
            Destroy(gameObject);
        }
    }
#

(Sorry for the huge code, not sure if it's ok to post all that :x)

#

Anyway, when I reuse the bullets from the pool, it appears the direction of the bullet does not get properly overwritten and still flies toward its previous path?

#

Would anybody know what's causing the problem?

#

I forgot to mention I'm using Unity PlayerInputManager to allow split screen so I have up to 4 players. Currently, both players are linked to my mouse and shooting at the same time for easier testing.

#

But I'm assuming split screen shouldn't impact pooling logic anyway.

fervent furnace
#

the videos seem showing the correct result, the bullet from red guy and green guy fly to different directions
I cant really get what are the differences, and i wonder how your pool looks like

knotty sun
fervent furnace
#

i see the velocity is resetted in Explode

next sparrow
#

What do I need to do then?

knotty sun
#

because you use ForceMode.VelocityChange

next sparrow
next sparrow
knotty sun
heady iris
#

it's equivalent to just adding to the rigidbody's velocity

#

except that it will be applied in the next physics update, rather than immediately

#

Force and Acceleration are for steady forces. Impulse and VelocityChange are for instant changes.
Force and Impulse care about mass. Acceleration and VelocityChange ignore mass.

next sparrow
#

In my second test, bullets just flies to random previous target. Even though I change the aim direction of the pooled bullet in Setup

#

This is the confusing part.

next sparrow
spiral ibex
heady iris
knotty sun
heady iris
#

I'm unsure how rigidbodies behave when their gameobject gets deactivated and activated like that.

knotty sun
#

exactly^

heady iris
#

You could always log the velocity when you fire to check if it's zero or not.

heady iris
#

I can't say if that's relevant here

next sparrow
#

Ok, using kinematic true then false did reset the velocity. VEctor3.zero did not.

#

Just before adding force]

#

But now, I have another issue

#

In my weapon Shoot, I'm supposed to take the first bullet in the pool and remove it from the pool.

#

But somehow, and only somtimes, both player use the same bullet when I click.

#

Meaning that sometimes, randomly, bullets are not fired at all for one of the soldier.

#

I'm not sure how it's possible. Shouldn't the Shoot method triggers one after the other when players shoot?

open charm
#

I need some help with code for reflecting and multipling objects

#

So Im trying to make it so that when a projectile hits a certain collider, itll make a duplicate projectile that shoots off at a slightly different angle

#

But I cant seem to make it so calculate the new trajectory of the new projectile

#
private void multiplyBullets(Vector2 originalDirection, GameObject bullet)
    {
        bullet.GetComponent<BaseBulletBehavior>().isMultiplied = true;
        int bulletMultiplier = PlayerManager.GetInstance().bulletMultiplier;
        Rigidbody2D baseRb= bullet.GetComponent<Rigidbody2D>();
        float baseRotation = baseRb.transform.rotation.eulerAngles.z;

        float offset = 2f;

        for (int i = 0; i < bulletMultiplier; i++)
        {
            float newRotation;

            if (i % 2 == 0)
            {
                newRotation = baseRotation + offset;
            }
            else
            {
                newRotation = baseRotation - offset;
            }
            
            Vector3 eulerRotation = new Vector3(0f, 0f, newRotation);
            Quaternion rotationQuaternion = Quaternion.Euler(eulerRotation);

            GameObject childbullet = Instantiate(bullet, transform.position, rotationQuaternion);
            Rigidbody2D childRb = childbullet.GetComponent<Rigidbody2D>();

            Vector2 spreadAngle = Quaternion.Euler(0f, 0f, newRotation) * Vector2.up;

            childRb.velocity = spreadAngle * bullet.GetComponent<BaseBulletBehavior>().bulletSpeed;
            childbullet.transform.right = spreadAngle;
        }
    }

Atm im using smth like this

#

But after testing it it definitely because the rotation that is obtained is before it is reflected by the colldier so the new projectiles jsut break as it doesnt get reflected

#

So im trying to find a way to obtain the new trajectory once the projectile bounces off

#

how do I go about doing that

latent latch
#

Not seeing any normal calculations

#

Basically you grab the contact points when you collide and create a vector from the normals

#

Or are you having trouble with instantiating new bullets here because they are too close to the collision?

open charm
#

So the bullets would not collide with one another just with the collider

#

So I dont think spawning them too close would be that much of an issue

open charm
next sparrow
latent latch
#

If you're using collision, I'm not sure if trigger colliders work though

next sparrow
#

The collision parameter has a property with the contact points

open charm
#

damn im using triggers rn

latent latch
#

It should have contacts

#

I think? I know you can do it by collider.ClosestPoint

mellow forge
#

guys can i use C++ in unity

open charm
#

Ill check

#

So i think it does by using clostspoint()

#

But how do I check the new trajectory afterward

latent latch
#

yeah doesn't seem like trigger colliders have them

open charm
#

shoot

#

Any ideas then?

knotty sun
mellow forge
knotty sun
#

directly supports, yes

silk spruce
#

[not sure what the best channel to ask is]

so i work at a company that does games adjacent stuff. interactive education and training sorts of things, especially in the life sciences. Our tools and workflows look like game dev all up and down.

my boss is lately pushing real hard to get everybody at the company to adopt AI into our workflows, and take advantage of the emerging tech sooner rather than later.

as a programmer, i ask chat gpt to throw together some boilerplate code every now and then when i'm using a tool i'm not familiar with, or when the task is relatively simple. But that's by far the minority of the work i end up doing, and it rapidly gets less useful and less accurate as the request gets more complicated. it's not even possible to ask gpt for help once there's more than one script involved.

is anyone here actually using AI tools routinely in their workflow?

I'd love to just shrug and ignore this, but this push for AI workflows isn't going away and i'm sure I could appease my boss if i had just one robust example to talk about.

vagrant blade
#

Just get Copilot and call it done

#

Beyond that, as you said, beyond basic things there's nothing ChatGPT is going to be speed up

latent latch
# open charm shoot

You can do closestpointonbounds, but may want to look around for a more accurate way. The reason why contact points are nice is because you can get an average of points so you can make an average normalized vector from that. I guess you can raycast a bunch when you collide as well around the surface.

#

depends how accurate you want to be with ricocheting

#

Actually, if it's just a bullet then it's probably fine. Not like there's much surface area to it all.

mellow forge
knotty sun
mellow forge
mellow forge
rigid island
mellow forge
#

is it easy to use C++ in godot?

#

or do i use flaxengine

rigid island
#

no idea

mellow forge
#

thanks for your time

rigid island
#

flax seems more intergrated with C++ so go with that or UE

lunar acorn
#

Am doing something wrong?, why cant you iterate through Lobby Changes? I am having so much more trouble with Unity netcode than with photon.

somber tapir
lucid valley
knotty sun
#

PlayerJoined.value?

lunar acorn
#

Thank you! Is there an easy way for me to inspect these classes in VS to see that I have to add 'value' next time?

leaden ice
knotty sun
#

or just read the docs

lunar acorn
#

Thank you both

shut kestrel
#

How do i do the same effect of GetKey in the new input system with a composite value, up, down, left, right setup in the action map, i want to be able to keep moving my player while holding down the button but it only triggers once

latent latch
#

new input system is less about continous callbacks / polling and more about subscribing and unsubscribing

#

perhaps there's been more methods of input since I last check, but ideally you'd subscribe on first input and unsubscribe when you let go of the input

#

not too sure how analog support works with it though

shut kestrel
#

yea, i am using invoke unity events behaviour in the new input system so i did subscribe/unsubscribed the methods, everything works beside the continuous trigger effect

latent latch
somber tapir
shut kestrel
#

so i would have to use the update method inevitably then? i was trying to avoid using it but if not possible i guess will do that thanks

spring creek
leaden ice
#

if you need something done every frame (such as moving), Update is still the natural place for that.

shut kestrel
#

Alright, thanks for all the answers

kind basalt
#

is there some better way to have methods get called in sync with animations aside from using animation events? I feel like using a bunch of animation events to call various methods is not a good idea, is this really the best practice?

#

is there any way to have the script like call an animation and method if the animation finishes without using an animation event?

leaden ice
steady moat
kind basalt
kind basalt
# steady moat StateMachineBehaviour is the way to go as stated by someone else.

and great, is this the best practice for animations and timing this accordingly like game logic? I get like using the animation to change the sprite red for damage makes sense as being controlled in the animation events, but game logic like shooting a bullet seems a bit tough to manage if its controlled by an animation

steady moat
#

The easiest way is to control the animation 100% through your own statemachine.

kind basalt
#

cool thanks

#

so if I had a death animation lets say that ended by calling a method to destroy the game object, would the best practice be to just add the logic in the script (like cantwalk, remove collider, cant attack) while we are waiting for the game object to be destoryed, just so that animation won't be interrupted? @steady moat

steady moat
#

At that start of each state (In your code - Death, Idle, Attack), you switch to the appropriate Animator State.

kind basalt
burnt oar
#

hjelp 😔 /j

spring creek
burnt oar
#

not nessesarily, is there a channel for funnies?

spring creek
burnt oar
#

my bad

#

the joke was the demon shader i summoned via negative gradient scale

hard viper
#

let’s say a bomb explostion is going to push someone in a 2D sidescroller. the direction of the force should probably be locked to 8 directions? or 4?

hard viper
#

consistency

steady moat
#

Not sure what makes it consistent

hard viper
#

so if player throws or triggers a bomb, and it’s a bit off, the angle of whatever gets pushed effectively gets rounded to the same direction

steady moat
#

More like a question of design, but I do not think it makes thing more consistent.

#

I'm expecting object to get push in the inverse of direction from where the explosion is.

hard viper
#

the challenge here is mostly when everything is going fast, and the distance is very small, so the angle is very sensitive to small differences

kind basalt
#

is your movement system actually locked in 8 directions?

hard viper
#

no

kind basalt
#

if you aren't moving on a grid i dont think that makes sense

hard viper
#

objects in the world spawn in a cartesian grid tho

kind basalt
#

it may feel off for the player, but not really a question of code

steady moat
hard viper
#

so initial positions for all the objects is locked to a grid, but then things can freely move

kind basalt
#

so are you snapping the player to the grind at all time, like a chess piece that must be on the 0,0 of a square ?

hard viper
#

no, but some blocks in the world are snapped to grid

steady moat
#

If we are really talking about really, really small change, then you might look into Numerical stability to see if there is anything that you can do to fix your algorithm.

native fable
#

How to load and autoimport package from server?

I have server with several .unitypackage files. I want to load this files from server and then import this files to my project.

zinc parrot
#

if I use OnRenderImage to render using compute shaders, is there any way to have this happen before postprocessing so I can apply postprocessing to it, or is there a way better than onrenderimage that works? unity 2021 builtin

rigid island
knotty sun
late lion
stable kayak
#

do you guys think 20~ish seconds to load a 100x100 tile stage is taking too long for a modern computer?

zinc parrot
#

I need it to run off a monobehavior script

late lion
kind basalt
#

whats the best practice for giving a player an ability from a set of like 100 abilities, is it to make a gameobject with the script and instantiate it as a child or is it to hold the information somewhere as a variable like playerAbility1 = swordswing?

zinc parrot
#

oooo ok!

late lion
stable kayak
# late lion If it's a basic 2D tilemap game, then yes.

any suggestions on fixing this? currently I'm loading from json (level editor saves to json), each tile stores 3 game object (every layer has a tile that has 2 images (base tile + animated sprite)

at present I'm instantiating the game objects when loading, should I
a) divide into chunks and load the player first
b) do a whole loading entirely
c) something idk

#

oh i'm also spawning about 1000 enemies

#

and a bunch of gameplay objects like breakables, treasures, etc

#

to be clear the actual game isn't that crazy, this is a stress test, but I'm perplexed that its taking 20 seconds to load

winter night
#

Howdy. I am working on custom editor stuff and have run into the issue of not being able to add an enum to the custom editor script. I have tried a couple variations I found online but I cant seem to get anything that works. Here is the line I am using
levelController.startingLvl = EditorGUILayout.EnumFlagsField("First Shed Door Close Trigger :", levelController.startingLvl, typeof(Enum), true);
levelController is the script I am making the editor for
startingLvl is the enum

Does anyone have a solution?

somber nacelle
winter night
#

Totally missed that channel. Ty

clear umbra
#

Hey guys, I'm building a unity game for ios and embedding it in a react-native project.

I'm trying to make my dev flow as automated as possible, I'm wondering about two things:

  1. is it necessary to rebuild the Unity project to an XCode project each time I make changes to the scene/scripts
    aka is it necessary to do the following each time: File -> Build Settings -> Build -> Select folder -> Append the build

  2. If it is necessary to do the above each time my scripts/scene change, can I automate the process to build the XCode project from the command line? I'd rather invoke a script than to go through all these menus

late lion
somber nacelle
stable kayak
#

so I guess the main question now is, how do I cut down on time taken to read the json

lean sail
stable kayak
knotty sun
#

binary serialization

stable kayak
#

thanks, I'll look into it

raven vault
#

Does anyone know why my unity package icons arent showing up?

#

things work still and function. just the icons wont work for any unity items, i can change them to other things like 7-zip, etc. But they wont change to unity

somber nacelle
#

that's not a code question. and it's likely because your OS hasn't been told what to use to open those files

knotty sun
#

what do you mean 'icons wont work'? Icons are just pretty little pictures and have no function whatsoever

raven vault
#

icons for anything unity dont show up visually, and i was just wondering if there was a fix to it, but i'll find it

heady iris
#

This is not a code problem.

raven vault
#

i know thats why im jumping out............

heady iris
#

oh, my bad, i missed box's reply

whole flicker
#

What happens to my UI code when I build for dedicated server? for example a listener to a button, that wont be needed on my server, is that still running on the server and wasting resources?

rain minnow
kind basalt
lean sail
# kind basalt abilities are chosen throughout playtime, roguelike style: level compete pick an...

You probably need to first think more about how you want this working gameplay wise. For example if the player has only 4 abilities at one time, you need some way for it to choose which ability to overwrite. If they can take as many as they want, you need some way to use a variable amount of abilities. Then you can design code for how to use abilities. Once you make code to use abilities, then you can pick abilities whether that overwrites or adds to your current ones.
I think having it as a monobehaviour is fine honestly, let's you use unity inspector more even if you dont need the unity functions.

late drum
#

My game works fine in the editor, but when I go to build it im getting the error "The type or namespace "SceneAsset" could not be found". I have assembly files for each of my scenes, but my Level manager has drag and drop SceneAsset references. I have using UnityEngine; and declare it as public SceneAsset scene; And it works in editor play. Can I not use SceneAsset in a build?

lean sail
#

You can use a string from the scene asset, and surround the scene asset stuff in a conditional

fair charm
#

The entire UnityEditor namespace cannot be used in build. Scripts that use this namespace are normally placed in "Editor" folders that are not compiled into the build.

lean sail
#

You mean unity editor?

fair charm
#

Yes. my bad.

late drum
heady iris
#

It lets you drop in a Scene asset and then get its name at runtime

kind basalt
late drum
#

Okay thanks for the help. Thats a shame this is editor only

lean sail
heady iris
#

I think the easiest way to do this is to just make each ability a MonoBehaviour

#

then you can make a prefab for each ability and drag the ones you want onto the player

lean sail
#

Sometimes I try to make things POCO but it's so much nicer being able to drag instances around lol

heady iris
#

yeah

#

(plain old C# object)

#

I sometimes use [SerializeReference] to serialize plain old objects, but I often wind up needing unity objects anyway

#

e.g. I want to be able to assign a reference to the ability somewhere

kind basalt
#

so are we getting the ability script through the game object thats attached to the player? or do we run the script from the list of 100 or whatever abilities in the game like player pressed Q, so we call ability 27 to run?

heady iris
#

I would give the player a list of Ability

#

where Ability is an abstract class deriving from MonoBehaviour

#

anything in that list can be activated

#

I'd make a game object to hold each component and parent them to the player somewhere

#

Not every game object needs to correspond to a tangible "thing"

kind basalt
#

yeah

heady iris
#

I have a whole hierarchy of "non-things" in my game

#

game globals -> managers -> [many objects holding singleton components]

void basalt
lean sail
#

That is pretty much what I do right now, it does somewhat get awkward if enemies though are not limited to 4 and you have to change the system

kind basalt
#

interesting, very helpful hearing your info about this thanks a lot

heady iris
#

In that case, I'd separate the player/AI control from the actual character

#

the player control component would use four input actions to activate each ability; AI would just pick randomly from the entire list, or whatever

latent latch
kind basalt
latent latch
#

thank god for reusability

#

Basically just scriptable objects, but if you don't want the project bloat then serialize reference work too

#

new Ability<AbilitySO> then cache myself a particle pool

kind basalt
#

interesting

heady iris
#

one problem with using generics like that -- you can no longer have a List<Ability>

#

since Ability by itself isn't a valid type

latent latch
#

interfaces ;)

heady iris
#

serializing interface types is annoying

latent latch
#

honestly, I could do without, but I feel like it makes sense to always had a SO coupling contraint to each class that requires a data asset

stable kayak
latent latch
hard viper
#

is there a decent workaround for not being able to assign Vector2 or Color with default argument values?

#

or do I just need to make a whole new overload?

somber nacelle
#

just make an overload without that parameter that just calls the other overload and passes your desired default value

#
public void SomeMethod(Color whatever)
{
  //do work
}
public void SomeMethod() => SomeMethod(Color.white);
opaque spear
#

Can someone tell me if this is a unity bug? Why would selecting them cause their enum values to be set to 0?
` public class SoundData : MonoBehaviour
{
public AudioSource AudioSource;
public SoundId SoundId;
}

public enum SoundId
{
    Unknown = 0,
    Bounce = 10,
    Bounce2 = 11,
    Jump = 20,
    Dash = 30,
    AnnouncerReady = 40
}`
latent latch
#

It's a enum editor thing

#

I think it's just how it's serialized was it? But try keeping the values orderly.

split furnace
#

Hi. I'm making a charging enemy that has to hit mulitple targets. they seam to hit the player more then 10 times. is there anyway way to limit it once?

latent latch
#

Depends how you want to do it, such as giving a player some invincibility frames, or making it so that specific enemy can't damage the player again (in a short span of time?)

split furnace
#

the enemy can't damage the player after their charge attack is done

latent latch
#

If it's enemy specific then you should add an internal flag to that enemy such as hasAttacked or something similar which you will check as they try to continously damage the player

split furnace
#

i tried that. that what currentTarget is supposed to do but it ignores it because it repeats that void over and over again

latent latch
#

Oh I see. Do you have multiple player's in your game here?

split furnace
#

funny thing is, I just put in a bool and it worked

latent latch
#

trying to understand this container, but if you got it working

split furnace
latent latch
#

I think I'd have a container of HealthPlayers, and if it went into that first statement I'd just append them to a new list which I'd check every next iteration

maiden hatch
#

This discord is so great, after trying to find a solution to my problem for a hour, I decided to ask for help here, but I found the solution by just explaining the problem 😂

lavish magnet
#

I finished my game anti-cheat 😄

#

My friend tested it.

heady iris
#

it forces you to think about your problem enough to explain it

lavish magnet
opaque spear
somber nacelle
#

submit a !bug report

tawny elkBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

latent latch
#

I was trying to reproduce that but I must be thinking of another bug

somber nacelle
#

I've got a question about default interface methods that I cannot seem to find an answer to online.
say I've got an interface that has a default method implementation on it and i've got a class that implements the interface, i want that method to do something extra rather than something different, so i want the default behavior and then some extra behavior that other objects implementing the interface don't need.
I can't seem to find a way to accomplish this without just explicitly implementing the interface method and copy/pasting the default implementation into the new implementation

is that really my only option if i don't want to turn the interface into an abstract class to inherit from?

opaque spear
somber nacelle
hard viper
#

I made a VisualEffect with visualeffect component, that works on a prefab, works if I drag it into the scene, but doesn't work if I instantiate the gameobject. Any advice?

latent latch
#

odd, what's the error

hard viper
#

I've had this issue before, but don't know how I did it 2 months ago

leaden ice
hard viper
#

the VFX just don't display on an object that is instantiated via prefab

somber nacelle
hard viper
#

I remember the solution being some really dumb checkbox in a menu in the VFX graph, I think? But i have no idea where it would be

latent latch
#

vfx graph has some cold start or something, and I find stuff not rendering right away.

#

not really instance related, I think it's specific to the asset

#

I think I've read people will load each system at the start of the game then remove them from the scene

hard viper
#

well, I can drag my prefab into the scene, but it won't show

zinc parrot
hard viper
latent latch
#

strange. Only thing I can think of is you got some restriction on them and preventing them from playing

#

limited by spawned particles, paused, ect

kind basalt
#

in unity 2d for top down, what's the best way to create an effect with a paralax on a background image or tileset like this:

swift ocean
#

i have watched the same 20 minute tutorial for the entire month and i still can't comprehend

#

my brain just goes blank after 4 to 6 minutes

#

i could stare at a wall for 10 hours and it wouldn't be as painful

#

i just don't understand why i can't seem to get motivated, throughout my 3 years of game dev i only got as few as 5 months of actual work

#

i don't care, i was born to make games, even if my progress would take 10 times more time

lime thistle
#
        dashing = true;
        velocity = new Vector3(transform.forward.x * dashingPower, 0f, transform.forward.z * dashingPower);
        yield return new WaitForSeconds(dashingTime);
        velocity = Vector3.zero;
        yield return new WaitForSeconds(dashingCooldown);
        
        dashing = false;

how would i make this instead be an 8-way dash? with the direction based on the wasd input

somber nacelle
#

instead of using transform.forward for the direction of movement, use your input. you'll likely need to use transform.TransformDirection to convert the input to world space direction first though

polar marten
polar marten
#

can you call base.DefaultEffect() or IFoo.DefaultEffect()? I'm not sure. you can in java

#

you are better off using abstract base classes

half saddle
#

I'm not sure the proper way to cancel this async function when its MonoBehavior has been destroyed. This throws an error which makes me believe I'm doing something wrong.

private async void SpawnEnergy()
{
    while (true)
    {
        await Task.Delay(5000, destroyCancellationToken);
        GameObject orbGameobject = Instantiate(orbPrefab, transform.position, Quaternion.identity);
        Rigidbody orbRigidbody = orbGameobject.GetComponent<Rigidbody>();
        orbRigidbody.AddForce(transform.forward, ForceMode.Impulse);
    }
}
somber nacelle
polar marten
#

i see

#

i assume internally c# makes an instance which implements the defaults

#

i understand why you cannot call into it because the interface implementor is not inheriting from that type

hard viper
#

i can drag my prefab into the scene, and it works fine. but if my code instantiates it, the VFX do not display, even though aliveParticleCount is 20-400.

polar marten
#

Tasks are complicated. what do you expect cancelling while Task.Delay is being awaited to do?

  1. The method "just" "stops" executing without any further baggage, like coroutines.
  2. Task.Delay throws an OperationCancelledException
  3. Task.Delay returns immediately and destroyCancellationToken.IsCancellationRequested returns true. then, since the game object is destroyed, transform.position throws a NullReferenceException
hard viper
#

My particle output had Orient to Camera, and I changed to a custom axis. idk why this made a difference, but it was indeed something dumb.

robust mantle
#

Hi, I'm starting to learn how to make meshes from code, I want to know how I can get the direction from one vertice to all vertices connected(all the edges). How do we get this information from a mesh and its vertices?

clever lagoon
robust mantle
merry sierra
#

do anyone know how to remove the interactable from xrsocket at runtime like by pressing the button

half saddle
# polar marten what is the error?

I'm sorry, I can't believe I left the error out. The error is "TaskCanceledException: A task was canceled". I expect the method to stop executing, like a coroutine. This happens when I stop running my program, so Destroy() is never called by me explicitly.

polar marten
#

you have to catch it and return

half saddle
#

Really?

#

That's kinda weird isn't it

polar marten
#

so

async void Blah() {
 try {
   your code
 } catch (OperationCancelledException) {
 }
}
polar marten
#

it's not

#

it makes a lot of sense

#

think about the other situations i described

#

what do you expect to happen? gotta answer my question

half saddle
#

I said I expect the method to stop executing, like a coroutine.

#

Without baggage, that is

#

I expect in most use cases throwing an error for a task is useful, not so much for stuff like this

vapid helm
#

What's the most efficient way to code a timer for a game? Running it from fixed/update would slow it down or would that be negligible?

clever lagoon
#

like you want somthing to happen when the timer elapses? Update should be fine for that, as long as you don't have too many of them active at once.

vapid helm
#

If its just that it should be fine then right?

clever lagoon
#

yes

#

I'd use Time.time for that tho. record it on start, then subtract to get current "survive time"

vapid helm
#

Nice thank you 😊

clever lagoon
spring creek
# vapid helm Timer that counts how long you have survived, and displays it during the run.

Keep in mind that Time.time is the time since the application started. So you would need to handle cases where the player can stop the game and come back later. That is very simple, just a consideration

But adding to a timer in Update or FixedUpdate is completely negligable too. Every piece of code you write occupies the main thread and technically "slows down" the game, but computers (even phones) are extremely fast. Adding a float to another float once a frame is, as said, completely negligable
Efficiency for something like that shouldn't really even need to be considered.
Profile things and fix them when they are an issue

untold rapids
#

quick question how can i stop my animation from endlessly looping

unreal temple
#

We're getting this error when building on macOS in Unity 2022.3.12
Has anyone seen this before? I believe it's only happening on one person's computer.

Building /Users/angusarnold/Desktop/MasterBuild.app/Contents/MacOS/Enter the Chronosphere failed with output:
System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.)
 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at UnityEditor.OSXStandalone.CodeSigning.HashUtils.WriteHashString(Byte[] data) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 41
   at UnityEditor.OSXStandalone.CodeSigning.HashUtils.HashFile(NPath file, Byte[]& sha1Hash, Byte[]& sha256Hash) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 148
   at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.SignResourceFile(FileToSign file) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 243
   at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.<>c__DisplayClass9_1.<SignFilesWide>b__0() in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 193
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, 
[13:36]
ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.SignFilesWide(IReadOnlyCollection`1 files, Boolean warnAboutUnsignedChildBinariesInBundle) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 213
   at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.Sign(SignFlags signFlags, BundleSignTarget& signedBundle) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 59
   at MacOSCodeSignBundleInPlace.Run(CSharpActionContext ctx, Data data) in /Users/bokken/build/output/unity/unity/Platforms/OSX/MacStandalonePlayerBuildProgram/MacOSCodeSigning.cs:line 109

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) (at /Users/bokken/build/output/unity/unity/Modules/IMGUI/GUIUtility.cs:190)
spring creek
west sparrow
unreal temple
#

Not a release

#

So ideally we don't need to sign at all, but I'm not sure how to disable it

half saddle
loud wharf
#

Why on earth would a try catch block crash. UnityChanThink

vagrant lake
#

hey so i have 2 questions

  1. how do i make it so that my camera doesn't clip through walls while wall running?

  2. how do i make the player not able to stick to walls when pressing A or D depending on which side the wall is on from them?

I have the wall running script so just ask if you need it please, i dont want to fill up the chat with a giant wall of code

vagrant lake
#

Ok thank you

prime quarry
#

Hi i find myself trying to force my design patters im used to in game maker onto unity. For example in game maker inside game maker you could just go and say enemyTarget=instanceNearest(objEnemy,x,y) and then u csn say enemyTarget.BecomeDammaged(attackStrength);

#

So within one object you can entirely control another

#

But ive noticed in unity doing that is a whole ass exercise

#

So i was wondering maybe there is a better way to do this in unity

#

So i dont have to forcefully go thru all the scripts of the object then find said method then try and use it

fervent furnace
#

why you cant do that in unity?.....

lean sail
# prime quarry So i was wondering maybe there is a better way to do this in unity

you havent really described what "this" is, i believe i suggested in a previous conversation to just use triggers to get nearby targets (and then you can sort it if u wish). This pushes your logic to another object, since you want this script on the same gameobject as your trigger collider. Whatever object does damage would also call GetComponent to look for a health script, which would likely happen on collision/trigger or raycast

lean sail
prime quarry
#

Well the instance nearest isnt really the important part the important part is you can just find the object id and then immediately begin changing its fields firing its functions,in Unity having to search through all the scripts and then all the functions to see if it even exists before using it feels wrong

#

Like im not coding correctly

fervent furnace
#

you can reference specific component?

lean sail
#

search through all the scripts and then all the functions to see if it even exists
It is one single GetComponent call if you are talking about getting a reference on a totally unknown gameobject

#

if we are talking about the same object, you just drag in the reference in the inspector

dusk apex
#

What's the actual problem?

prime quarry
#

What if you dont know the name of the script for example if the nearest object could be orc or skeleton one has a orcController script the other skeletonController script now you cant reference the script directly because you dont know which name it is

fervent furnace
#

TryGetComponent and test the tag of the gameobject
Btw why you dont know the script of the gameobject

prime quarry
#

Also im not trying to say game maker is better im trying to say maybe game maker taught me bad coding practices and I am trying to learn better ones

lean sail
prime quarry
prime quarry
fervent furnace
#

read what bawsi say, you may need inheritance.

prime quarry
#

Ive been having just one script per object

#

Sorry i posted that reply just as he replied

lean sail
#

Health is health, doesnt matter if it is a skeleton, orc, a wall you want to break. They all work the same, you hit it, it takes damage

prime quarry
#

I see , thank you i knew i was doing something wrong

#

Also my bad this should have been in the beginner channel

lean sail
prime quarry
#

Unity seems to live much more in its IDE UI than game maker

lean sail
# prime quarry Unity seems to live much more in its IDE UI than game maker

You can definitely use the inspector to setup very different enemies. you mentioned skeletonController and orcController before, but in unity you can pretty much just make one "AICharacter" script if you make your other code generic enough. The difference between a skeleton and orc is only the model and collider size. If you have a way to assign the attacks they can do in inspector, then there is no code different between them.
Also having health as its own component lets you setup other nice things, like if you want a skeleton that cannot be damaged (maybe it is a town NPC), then you simply dont add the health component. If you want a skeleton thats used in battle, it can have a health component. The AI code doesnt change

onyx berry
#

I have a prefab of road, it gets destroyed with a trigger collider, when a new prefab of road is instantiated, it does not get destroyed by that collider. Why is that? Need help

fervent furnace
#

We dont know without seeing your scene setup and code

loud wharf
#

First of all, i'm not sure if u should be using the names of gameobjects as ids if that's what you're thinking.

loud wharf
lean sail
loud wharf
#

true. 🍿

#

Making my own game engine, gonna use composition for dictating parent/child hierarchies.

drifting crest
#

Hi i am trying to make a video player where when user hovers with their sprite then only it is visible so I am playiing a video on one sprite and and enabling one plain sprite on that video player sprite but when I am hovering with my sprite the video isn't visible

frozen vale
#

Hi everyone, I'm trying to rotate an object in a way that its transform.up would be aligned with the normal of the ground it is standing on, and at the same time indepedently rotate it around the y axis in order to reach a certain target.
When I do these rotations separately on my object, they work perfectly, but when I add them together, one of them always decides not to work properly.
In this implementation, the y rotation works, but the normal doesn't.

Any help would be greatly appreciated! 😃

Code snippet:

//Calculate the rotation based on the Y axis rotation
Quaternion yRotation = Quaternion.Euler(0, Time.deltaTime * currentAngularVelocity, 0);

//Calculate normal
Vector3 v1 = rightLegTargets[0].transform.position - leftLegTargets[^1].transform.position;
Vector3 v2 = rightLegTargets[^1].transform.position - leftLegTargets[0].transform.position;
Vector3 normal = Vector3.Cross(v1, v2).normalized;

//Calculate rotation to align transform.up with the normal vector
Quaternion normalRotation = Quaternion.LookRotation(transform.forward, normal);

//Combine the normal rotation and the Y-axis rotation
Quaternion combinedRotation = normalRotation * yRotation;
transform.rotation = combinedRotation;
onyx berry
# fervent furnace We dont know without seeing your scene setup and code

I'm using an empty game object, with a collider. It has trigger checked on collider property, and the script attached to the road prefab has

Inside update

Private void OnColliderEnter(Collider, other)
{
If(other.gameObject.CompareTag("Road_Destroy_Tag"))
{
Destroy(gameObject);
Debug.Log("Road Destroyed");
}

Now the Tag "Road_Destroy_Tag" is applied on the collider, that detects the road prefab in the scene. The first time I run play mode, it destroys the road prefab, and the console shows it, but as soon as the new prefab of road is instantiated, as it passes through the destroying collider, it don't get destroyed, and the console don't show anything. This means it only works once

fervent furnace
#

this is not even valid c# syntax

#

!code

tawny elkBOT
onyx berry
#

Private void OnColliderEnter(Collider, other)
{
If(other.gameObject.CompareTag("Road_Destroy_Tag"))
{
Destroy(gameObject);
Debug.Log("Road Destroyed");
}

onyx berry
fervent furnace
#

What is on collider enter, there is no such message in monobehaviour, we have on collision or on trigger

onyx berry
#

Oh my bad, it was onTriggerEnter. I memorized it wrong

fervent furnace
# onyx berry

Check the method really got fired or not, and your ide seems not configured

onyx berry
#

Sure.

#

Thanks for the help

#

@fervent furnace

hollow hound
#

Not sure where to ask this, but how to disable alphabetical sort of serialized fields in rider?
It even says
<!-- Pattern to match classes used by Unity that contain serialised fields and event function methods. Based on the standard "Default Pattern", this will also order event functions before normal methods, and does not reorder serialised fields, as this order is reflected in the Unity editor's Inspector -->
in file layout setting.
But still sorts my [field: SerializeField]

slate trellis
#

I want to Intantiate a gameobject from the position of the player. The object acts as a projectile black hole. That causes the problem that when I try to summon the object, the player gets pulled in. This is intended behaviour, and such I don't want layer overrides. I just want to instantiate the gameObject a bit further up front (and possibly automatically adjusted depending on the radius value). What would be the best way to do that, since Vector3.forward just returns a fixed value and transform.forward a fixed axis?

Code:

// The attacking script
[SerializeField] Transform projectileSummon;
GameObject gluttony = Instantiate(Resources.Load("Prefabs/Gluttony") as GameObject, projectileSummon.position, projectileSummon.rotation);
        gluttony.GetComponent<GluttonyBehaviour>().player = gameObject;

// The behavior script is in the pastebin

https://pastebin.com/6Pqm4ys3

soft shard
# slate trellis I want to Intantiate a gameobject from the position of the player. The object ac...

Getting a fixed axis may actually be helpful if I understand your scenario correctly - if you know the direction you want to put the object away from the player, and you know how far in that direction, say youd want to spawn it "12 meters infront of the player", then transform.forward returns "1 meter from the player", so transform.forward * 12f would return 12 meters from them, so origin + (transform.forward * 12f) would be 12 meters in the players forward direction, from some "origin", in this case, that origin sounds like your players position

slate trellis
#

thanks a lot. You are a lifesaver

lunar acorn
#

I am unable to spawn GameObjects to clients. I get this error:

Unity.Netcode.NotListeningException: NetworkManager is not listening, start a server or host before spawning objects

lunar acorn
steel finch
#

so I'm currently generating resources on my map by doing the following :
choosing a random point on the map
Then casting a ray from the top of the map to the bottom of the map and generating a resource wherever it lands

how would I calculate the rotation of the resource based on the slope of the surface that the raycast hit?

slate trellis
#

you add \``` before and after the code\```

lunar acorn
#

how come it didnt work for my comment?

lunar acorn
lunar acorn
slate trellis
lunar acorn
somber nacelle
lunar acorn
carmine ridge
#

hey guys, not sure where to post it but i can't compile for linux dedicated server build using ILCPP on my MacOS, it hangs on forever at Linking GameAssembly.so (x64). Is there a known issue or a workaround for that ?

hard viper
#

are VFX components super expensive to instantiate or something?

#

I'm just noticing small lag spikes when I instantiate prefabs with a VisualEffect component on it

#

even if it is a super simple prefab with very little going on

restive ridge
#

im trying to make an equip and replace system in unity but im having the issue where weapons aren't getting replaced, rather just stack ontop of each other.

I already handle interactions in my controller script, here's the part related to guns

public void EquipGun(Transform gunTransform, Rigidbody gunRigidbody, BoxCollider gunCollider)
{
    if (gunIsEquipped)
    {
        DropGun(gunTransform, gunRigidbody, gunCollider);
    }

    gunIsEquipped = true;

    gunRigidbody.isKinematic = true;
    gunCollider.isTrigger = true;

    gunTransform.SetParent(gunContainer);

    gunTransform.localPosition = Vector3.zero;
    gunTransform.localEulerAngles = Vector3.zero;
}

public void DropGun(Transform gunTransform, Rigidbody gunRigidbody, BoxCollider gunCollider)
{
    gunRigidbody.isKinematic = false;
    gunCollider.isTrigger = false;

    gunTransform.SetParent(null);

    gunRigidbody.AddForce(playerCamera.transform.forward * dropForwardForce, ForceMode.Impulse);
    gunRigidbody.AddForce(playerCamera.transform.up * dropUpwardForce, ForceMode.Impulse);

    float random = UnityEngine.Random.Range(-1f, 1f);
    gunRigidbody.AddTorque(new Vector3(random, random, random) * 10);
}```

Here's the part in the gun script:

```cs
[SerializeField] private FPSController player;
private Rigidbody gunRigidbody;
private BoxCollider gunCollider;

private void Awake()
{
    gunRigidbody = GetComponent<Rigidbody>();
    gunCollider = GetComponent<BoxCollider>();
}
    
public override void OnInteract()
{
    player.EquipGun(gameObject.transform, gunRigidbody, gunCollider);
}```

I think i know what the problem is, in the first if statement, the script is referring to the gun already on the gorund therefore it doesnt drop anything, but im not sure how to store the already held gun's information for me to drop it. Or is there another way to do it?
hard viper
#

yeah, what I do is my equipping script has a few layers to it

#

I have an attacher script and attachment script.

#

Attacher script has a reference to what is attached, and an interface on itself to let it know that what it attached is destroyed or something.

#

Attached thing gets a simple monobehaviour (AttachementScript) to communicate with the attacher.
In order:
Call Attacher.TryAddAttachedThing(). This checks if we already have something attached. If we want to allow it to replace, we need to call CurrentAttachmentScript.DisconnectMe(). Then we add the newly attached thing, giving it an AttachmentScript component.

restive ridge
#

ooooo

hard viper
#

AttachmentScript.DisconnectMe() tells Attacher that the thing that is attached is disconnected, and to update its state automatically back to a blank state, where nothing is held

#

these aren't the names I use, but that's the general idea

restive ridge
#

yeah yeah i get it

hard viper
#

I use a generic IEntityAttacher interface so different things can use this mechanism. Not just player holding a gun or whatever

#

not actually a generic, but to be used by many things

restive ridge
#

dayum, thanks for the idea <3

hard viper
#

EntityAttachementHandler (the monobehaviour that goes on the gameobject), has a lot of separate little responsibilities for the attachement. Basically, it stores the state of the thing before it was grabbed, allows it to be changed, and sets it back if you drop it

#

for example, if you want to hold an item, and want player to not collide with it

#

EntityAttachmentHandler (when you tell it it is now being held by IEntityAttacher), can be set to automatically check for colliders, and disable collision between them. And it stores what it was before.

#

Then if you call the disconnect method, it brings the attached thing back to the original state.

#

This is the interface I use. Might be helpful to give you an idea:

public interface IEntityAttacher {
    /// <summary> Tell the attacher (parent) that its child has been disconnected.
    /// The argument tells you which handler specifically is requesting disconnection (in case of inter-transfer jank).</summary>
    public void DisconnectChild(EntityAttachmentHandler childRequesting);

    /// <summary> Return a reference to the child attachment handler that is currently attached. Return null if there is no child. </summary>
    public EntityAttachmentHandler childAttachmentHandler { get; }
    public GameObject gameObject { get; } // gameobject the script is on.
    /// <summary> Rigidbody for the attacher (parent). This may or may not be on the same gameObject! </summary>
    public Rigidbody2D AttacherRigidBody { get; }
}```
#

On small detail that should be obvious: Part of the whole point of this is to make sure the moment the parent dies etc that the child is immediately notified (to no longer have the properties of being held). And if child dies/destroyed/etc, it also immediately notifies parent that now nothing is attached (so it can hold something again).

#

The existence of the EntityAttachmentHandler script on a gameobject also indicates if something is already attached/held to something else.

#

eg you don’t want one player grabbing a gun out of an NPC’s hand

open charm
#

Im tryin to make some UI for my game

#

But I find that if I change the layout of my editor, the UI elements change a lot

#

SO I changed it to scale with screen szie

rigid island
#

huh ? where is the code question?

open charm
#

But then when I change it the UI became ridiculuously small

#

Oh Right maybe its better to ask in UI

rigid island
spring creek
#

Not really a code issue

terse turtle
spring creek
sullen drift
#

Excuse me guys, i have a question. I'm making a script where a certain part of the code is executed only when it's not in play mode (in Editor). So I'm using !EditorApplication.isPlaying as a check. If i add this to my script that uses MonoBehaviour, first question, will it able to check !EditorApplication.isPlaying if i turn off the play mode, second question, should i use #if UNITY_EDITOR #endif so it wont cause error when build?

fervent furnace
#

yes for both

sullen drift
#

wokey

#

okay i have an update, it seems its failed to run the method when editor is not in play mode

#

is there a reason to this?

#
        private void Update()
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                Reset();
            }
#endif
        }
crude mortar
#

Do you have the [ExecuteAlways] attribute on your class?

#

By default, methods like Update will not run in edit-mode

sullen drift
#

no, i already think of adding it, but the thing is, since its always run either in play or edit mode, wont it cost a heavy toll on the memories?

#

not to mention i have a certain game logic in this script, is there an another way?

heady iris
#

it will cost exactly as much as you make it cost

crude mortar
#

Depends on what you are trying to do

heady iris
#

Explain what you're trying to do.

#

not "run code when not in play mode"

#

what are you trying to accomplish?

dusk apex
#

As is, we can only interpret that you're wanting the code to always run - including in the editor (non play mode)

sullen drift
# heady iris not "run code when not in play mode"

i want to reset a certain value in my scripts variable when it stops play mode, because i have a static variable that stores some values, its more like a way to help my game designer not to make some human error mistakes. But overall in game, this value wont need to be reset, only when making levels or design in the editor. It stores some state that will persist on scene changes, thats why i made it as a static (i didnt use singleton pattern because of one and another conditions)

heady iris
#

If you want to reset something when you exit play mode, just subscribe to Application.quitting

#

you can conditionally do so with #if UNITY_EDITOR so that it doesn't run in the built game, if that matters

sullen drift
#

i already made manual button to reset in editor, but someday my game designer would forget

heady iris
fervent furnace
#

there is a callback function when playmode change

sullen drift
#

imma read it

#

it works well, thank you for the helps

zinc parrot
#

Is there something better I can do than indexof(Texture) to find a matching texture in an array? I assume the comparison for texture obejcts is quite expensive but is there any other like hash value that doesnt change for the texture I can use instead?

somber tapir
leaden ice
zinc parrot
#

yeah looking into a dictionary now thanks!!

#

as this is pretty rough

#

should I use the instanceid of a texture for comparison/keys?

native folio
#

using unity authentication, how do i check if a saved session token is an anon account or linked to a username/password account?

rigid island
native folio
#

oh so if they signed in as a normal account, SignInAnonymouslyAsync() will sign them back into that emai;/password account?

rigid island
native folio
#

Dope

native folio
zinc parrot
#

Are there any memory worries or anything if I use dictionary<int, texture2d> vs list<texture2d>?

native folio
#

like cuz i wanna display a screen if they're logged in as anon

#

and another screen if they're logged in as another provider

#

like username/password

rigid island
native folio
#

are anon users not cached?

rigid island
#

they are

simple egret
zinc parrot
#

yeee I know thats what im using it for instead of list.indexof

rigid island
#

not compiled

swift falcon
somber tapir
#

they don't exist

simple egret
rigid island
zinc parrot
#

wait so its not much faster to do ListB[ListA.indexof(texture)] vs Dictionary(Texture.InstanceID)?

simple egret
#

In that specific case it is faster

zinc parrot
#

hmmm fair

#

need to profile

simple egret
#

But if you use the Dictionary value to get the key, you're doing it wrong. The Dictionary is backwards

zinc parrot
#

oh no sorry Im using the dictionary key as an index into related arrays
I go from key to value not from value to key

#

im just worried that theres some memory "gotchya" about dictionarys over lists I need to consider

simple egret
#

Don't use them backwards, and, they cannot be duplicate keys in one Dictionary

#

The second point is not an issue since you're using IDs

zinc parrot
#

yeee thats specifically why I wanted dictionarys really, the whole list and indexof was to check for duplicates

latent latch
#

wouldn't a hashset work fine too if you're just doing a ref lookup?

#

the thing with the list was linear searching, but if you're not using a kvp then the hashset should be fine.

#

either way they're usually similar

native folio
cunning moth
#

Can anyone recommend a nice events library that allows me to easily send data between objects?

#

I don't want to mess around in the inspector too much either..

somber nacelle
#

why do you need a library for that? just get a reference and either use events or just directly pass the data

cunning moth
#

I want to eventually plug in new systems easily

#

And I want to trigger multiple actions at once

#

e.g. on x event, i want to trigger an action on object a and b

somber nacelle
#

right so use events

cunning moth
#

Wouldn't I have to pass this event variable around to all objects though?

somber nacelle
#

you just need to get a reference to the object that has the event

cunning moth
somber nacelle
#

if you really insist on using some library, there are frameworks like extenject which allow you to set up dependency injection containers

#

the caveat to using things like that is that you don't need it unless you know you need it and know why you need it

cunning moth
somber nacelle
#

a vague "I want to eventually plug in new systems easily" isn't really enough to actually need something like that

cunning moth
#

interacts etc

#

I also want to not be dependent on the inspector

somber nacelle
#

why

#

the inspector gives you an incredibly easy to manage simple dependency injection

cunning moth
#

i work in many scenes and cant be bothered to drag references here and there (among other things)

rigid island
native folio
#

alr

#

does GetUnityId refer to username/acc system

#

i can get a bunch of different ids

#

but i can't see one related to username/password

rigid island
native folio
#

But can't anon accounts also have usernames?

rigid island
#

no

#

they just have an ID

native folio
#

Wat

#

I'm pretty sure my anon acc has a username

#

I added it tho, it's not by default tho

rigid island
native folio
#

I did await AuthenticationService.Instance.UpdatePlayerNameAsync("Player");

#

When I log in as anon for the first time

rigid island
#

PlayerName and username are different things @native folio

#

and yes Unity auto Generates a "unique" PlayerName regardless

#

username is exclusive to username/pass login

late lion
# cunning moth https://github.com/kyubuns/Kuchen I think I might be looking for something like ...

Yeah this isn't great since it's string based. This is similar but type based
https://github.com/PeturDarri/GenericEventBus

GitHub

A synchronous event bus for Unity, using strictly typed events and generics to reduce runtime overhead. - GitHub - PeturDarri/GenericEventBus: A synchronous event bus for Unity, using strictly type...

cunning moth
late lion
native folio
rigid island
#

How are you grabbing the name ?

native folio
#

AuthenticationService.Instance.PlayerName

rigid island
#

oh thats why

#
 var name = await AuthenticationService.Instance.GetPlayerNameAsync();
 Debug.Log(name);```
#

do this , should show you the name

#

I'm doing a whole video series on UGS/Player Accounts, I'm certain unity generates one each time blushie

native folio
#

trying rn

#

oh yeah it looks like it's random words?

rigid island
#

yeah it just throws random words + # numbers

native folio
#

neat

rigid island
#

😼

rigid island
native folio
#

🙏

rigid island
#

we need username searching asap 😮

native folio
#

Is there an event or something I can listen to detect when/if the player name changes?

rigid island
#

good question, not sure if there is a built in way or you'd have to manually keep track

native folio
#

ah

#

ok

#

so can u change username for accounts?

#

or only player name

rigid island
native folio
#

got it

#

btw is there anwyay to configure the default username for anon accounts?

#

like max length, etc?

native folio
rigid island
#

Oh actually Username i think can't be changed, and no you wouldn't be able to modify its min/max length

native folio
#

rip

#

and rip

#

but whatever, less work for me ig

#

is there a way toreset password?

rigid island
#

you would think Unity would think about this shit when they rollout features

#

sadly you can't do any of that shit with username/password

#

if you must have better control, I would just opt in for the Unity Player Accounts

#

which allows user to sign up with email and password + password resets n all that jazz

#

the upside is that Unity player Accounts also lets you sign up with Google/Apple too already integrated

#

so users only deal with those Identity provider

#

same reason why Username/password doesn't have Two-Step auth , its a very basic feature with bare minimum, and resetting a password isn't trivial thing (if you ever had to do this manually you know the pain)

#

the Unity Player Accounts signs in safely through the browser

#

looks something like this

#

i have this video if you want to see how it works
https://youtu.be/XVqYIFcjhLE?si=6xLIMWoZSI8PSIBV

0:33 - Installing Authentication Package
0:58 - Connect Project
1:14 - Adding Player Accounts to Identity
1:27 - Client ID from Dashboard
1:40 - LoginController script
3:26 - UILogin script
6:40 -Testing
6:55 - Google Login
7:05 - Logged In
7:21 - Exporting to android
8:22 - Testing Android
8:34 - Matching Ids

Quick disclaimer:
I usually don't...

▶ Play video
hard viper
#

i saw a video on storing passwords. the safest way is to not store passwords, and use another service with better safety, like Microsoft or Google SSO

#

what would be nice is if Unity had a feature to auto connect to whatever platform account you use. idk if that is a thing

#

like connect to steam profile, or PSN, or Nintendo, etc

rigid island
hard viper
#

oh cool. is it out?

rigid island
#

they already have these so far

#

I'm guesing nintendo / psn ones are harder because of NDA

hard viper
#

nice. I might regret asking this, but is is easy/fast to implement?

rigid island
#

easy as Pi

hard viper
#

nice

rigid island
#

if PSN /nintendo has sign in api you can prob use the OpenID/CustomID option

quartz folio
#

They may just not be listed there because the details are under NDA

rigid island
#

I mean it does say its already there. its probably hidden if you dont have approval /nda agreement

Unity Authentication currently supports the following identity providers: Apple, Apple Game Center, Google Play, Facebook, Steam, Oculus (Meta Quest), Nintendo Switch™, PlayStation 4 and 5, Xbox, OpenID Connect, and Unity Player Accounts.

#

ah yes..was just saying that

#

nice

lilac pilot
#

Hello. Can someone tell me pls if I can use the IgnoreCollision method to make the ray ignore objects with a specific tag. An example is below.

public class RaycastLearn : MonoBehaviour
{
    public string[] tagsToIgnore = { "Base", "Wall" };
    public GameObject[] objectsToIgnore;
    void Update()
    { 
        Vector3 rayOrigin = transform.position;
        Vector3 rayDirection = transform.forward;

        RaycastHit hit;

        foreach (string tagToIgnore in tagsToIgnore)
        {
            objectsToIgnore = GameObject.FindGameObjectsWithTag(tagToIgnore);
        }
        
        foreach (GameObject objToIgnore in objectsToIgnore)
        {
            Physics.IgnoreCollision(gameObject.GetComponent<Collider>(), objToIgnore.GetComponent<Collider>());
        }
        
        if (Physics.Raycast(rayOrigin, rayDirection, out hit, Mathf.Infinity))
        {
            Debug.Log("Hit object: " + hit.collider.gameObject.name);
        }

        Debug.DrawRay(rayOrigin, rayDirection * 10f, Color.green);
    }
}
rigid island
#

and ignore that layer

lilac pilot
#

mb, but can i do it like that?

rigid island
#

the way I said it ? sure thats why I said it lol

lilac pilot
lilac pilot
rigid island
#

ignoreCollision doesn't care about raycasts

#

it just ignores 2 colliders from each other

lilac pilot
#

bad(

lilac pilot
native folio
#

but like i dont want it to be branded with unity shit everywhere

rigid island
#

hmm yeah it's a pickle

#

do note that you can also use unity but make your own OpenID style auth

#

its more complex though so I just don't mind the unity auth

native folio
#

ic

marsh geode
#
move.isOn = g.All(x => x.GetComponent<Moving>().isEnabled);```

For context:
- `move` is a Toggle
- `g` is a GameObject array
- `.All` is a LINQ function
- `isEnabled` is a boolean

Would this work? I'm not too experienced with using this LINQ function
leaden ice
#

It will certainly compile and run

marsh geode
#

my intentions are to check if every single array's moving component is enabled

leaden ice
#

Then yes

marsh geode
#

thanks

#

do you know how to compare floats?

leaden ice
#

With comparison operators

#

< <= == >= >

Same as any other numerical type

marsh geode
#

not sure how to use that inside of a .All function though

#

something like this maybe? i'm not sure

g.All(x => x.GetComponent<Moving>().wait == x.GetComponent<Moving>().wait)```
#

although that doesn't really make sense\

leaden ice
#

What are you trying to do

#

All of the comparison operators return a bool

foggy cipher
#

this should get vertices and tris from the gpu right?

marsh geode
#

check if every single gameobject's moving component's wait paremeter is the same

leaden ice
#

They can directly be used in the All function

marsh geode
#

well no, because x is a gameobject

leaden ice
#

So? We're talking about comparison operators

marsh geode
#

how would I use them in a function like this that's what I'm confused about

leaden ice
#

Same way you're doing it now

#
float first = g[0]. GetComponent<Whatever>().wait;
bool allSame =g.All(x => x.GetComponent<Whatever>().wait == first);```
#

I'm typing on the phone

marsh geode
#

ohh sorry i completely forgot doing it that way and was trying to compare everything with everything if that makes sense

#

i've been coding for too long

#

anyways thanks

languid hound
#

Since handles are apparently only usable in editors is there a way to use them in normal scripts for builds?

#

I just want to be absolutely certain mainly because I don't want to have to code my own for actual use in builds

latent latch
#

can draw gizmos I think

somber nacelle
#

gizmos do not draw in builds

soft shard
# languid hound I just want to be absolutely certain mainly because I don't want to have to code...

Handles are a part of the UnityEditor namespace, anything a part of that namespace cannot be included ina build since Unity doesnt also package the entire editor with your games, so AFAIK there is no native way of including them though I believe raycasts can be included with Debug.DrawRay or Debug.DrawLine, there may also be assets or github projects that have in-build approaches, one somewhat "simple" approach that comes to mind is to use primitive shapes as wireframes, which you could do in a free program like Blender, this does mean your including a wireframe mesh in your builds and resizing that mesh and potentially the material to give it a color for a build, so youd likely want to use a unlit material so its not affected by shadows and lights in your scene, maybe a depth shader so it renders infront of other objects if that matters for you - though I could be wrong and there may be a way, just not one ive heard of

latent latch
#

oh well, there's immediate GL unity library

#

graphic library unity library yes

languid hound
#

I think I'd be able to draw a wireframe mesh with Gizmos but I'll look at the GL library. Thanks for the answers kind of disappointed its an editor only thing since it doesn't really seem that useful lol

rigid island
latent latch
#

graphic library library

#

dont mind me

rigid island
#

Lol ops

#

I meant class but yeah xD

languid hound
#

Quite frankly this looks terrifying

#

(It has the word matrix and I don't like that)

rigid island
#

Graphics mathhhs

languid hound
#

Real

rigid island
#

Good thing Unity has neat methods that do most of the work

jolly dune
#

I don't understand why the vertical input is being read

rigid island
jolly dune
rigid island
jolly dune
#

which doesn't make sense because it is reading the horizontal input

rigid island
jolly dune