#archived-code-general

1 messages ยท Page 60 of 1

main shuttle
#

Well equals and == is different for vector2's

#

Anyhow, I was wrong, sorry for the interrupt.

broken light
#

yeh but you can write your own equals implmentation with the interface

#

ok yeh their equals method worked - thanks

still mica
#

hi so im trying to make a simple dash that lerps your velocity back to where it was before dashing

#
Vector3 previousVel;

    private void StartDash() {
        if (isDashing) return;

        isDashing = true;

        previousVel = rb.velocity;

        rb.AddForce(dashForce * orientation.forward, ForceMode.Impulse);

        StartCoroutine(InterpolateVel());

        Invoke(nameof(StopDash), dashCooldown);
    }


    private IEnumerator InterpolateVel() {
        Debug.Log(rb.velocity);
        Debug.Log(previousVel);

        while(rb.velocity != previousVel) {
            rb.velocity = Vector3.Lerp(rb.velocity, previousVel, 0.2f);
            yield return null;
        }
    }


    private void StopDash() {
        isDashing = false;
        StopCoroutine(InterpolateVel());
    }
#

and in interpolateVel, rb.velocity and previousVel are always equal (that's the problem)

quartz folio
main shuttle
#

Also not how you use Lerp

quartz folio
still mica
#

k

swift falcon
#

Hello, I have a question: How do I reference different data types that are all enums; case: I want to use a serialize field that's an enum but that data type can change:


public enum Month
{
    Jan,
    Feb,
}
public enum Day
{
    Saturday,
    Sunday

}

I want to be able to reference wither of those types in the same place... how do I do that please
(I know about templates but I didn't find the way I need to be able to do this)

void fog
latent latch
#

Dictionary?

void fog
#

you can cast them to integers and to whatever enum type you want

swift falcon
swift falcon
quartz folio
#

I don't understand the question, are they meant to be serialized together? If so, just make a struct

swift falcon
#

no no @quartz folio

void fog
#

Yeah, im not understanding the ask

#

Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;

swift falcon
#

ok I will try to put it this way

void fog
#

thats a flagged enumeration

main shuttle
#

It's cs or csharp for the colours btw.

swift falcon
void fog
#

Are you referring to generics?

GetEnumValue<TEnumType>?

swift falcon
#

trying to explain what I am trying to do... I want to use a Data type.... like I have several game objects, I want them to have a variable that's either of weekdays or month ...

void fog
#

you want one or the other

#

you'd have to keep track of which one is which

swift falcon
#

yes

#

what do you mean

void fog
#

when structuring data, you use strongly typed objects

#

under the hood, enumerations are just whole numbers, binary representations if you use flags

#

the values for one enum dont directly map to another

#

so in order for you to prevent trying to deserialize to a specific enum that might not exist, you have to know the type

swift falcon
#

yes I want tio pick up the type in the beginning

void fog
#

what exactly is this enum for?

#

explain what the data looks like

swift falcon
#

so what I was thinking is referencing a datatype <T> that's an enum

void fog
#

you'd have to have your parent class handle generics as well to know which enum type its using

quartz folio
#

how are you expecting to actually use this thing

swift falcon
void fog
#

why do you need to goggle between two enum types?

#

thats not really an intended usage

#

you'd have a lookup table or something

#

your record would have a masked value to map out to those enums

#

tell us what you're doing with these enums

swift falcon
#

but thank you

#

it seems like i will have to do it that way

void fog
#

is there a reason why you arent telling us the usage?

swift falcon
#

there is more than one usage

void fog
#

enlighten us ๐Ÿ™‚

quartz folio
void fog
#

that will help us steer you in the right direction

swift falcon
#

the first is the simplest, I have a several dropdowns that I want to change their values depending on what they represent (the idea is easy here... just pick before the game launches in the inspector the data type )

void fog
#
public class ChosenDate
{
  public Month SelectedMonth {get;set;}
  public Day SelectedDay {get;set;}
}```
#

the ToString for enums by default will use the name value instead of the number

swift falcon
#

yes yes

void fog
#

eg Month.Jan.ToString() == "Jan"

swift falcon
#

but I dont want to referene both

void fog
#

how do you know which one to use?

quartz folio
#

Can you answer my question then

latent latch
#

You're going to probably need some type checking for what you're thinking of

void fog
#
public class ChosenDate<TEnum>
{
  TEnum SelectedValue {get;set;}
}```
swift falcon
latent latch
#

If you want to do it in the inspector, that seems a little more complicated.

quartz folio
#

still no idea how this code is meant to be used when you actually have the type

#

which I have asked 3 times now

void fog
#
public class DateSelector
{
  Type ChosenEnumType {get;set;}
  int RawValue {get;set;}
}```
but you'd have to cast from the int to the type with reflection or something
#

and you'd have to tell the inspector what the list of viable types are

void fog
quartz folio
#
[Serializable]
public struct DayOrMonth
{
    [SerializeField] private bool _isDay;
    [SerializeField] private Day _day;
    [SerializeField] private Month _month;

    public bool TryGetDay(out Day day)
    {
        day = _day;
        return _isDay;
    }
    
    public bool TryGetMonth(out Month month)
    {
        month = _month;
        return !_isDay;
    }
}```
and then make a property drawer for it
swift falcon
void fog
#

...

swift falcon
swift falcon
quartz folio
#

well, you've been provided many different answers and little information so until there's actually an answer to our questions nobody can help you

void fog
quartz folio
#

No idea why you want inheritance when this takes up the space of what, two bytes and a bit?

void fog
#

ehh, you have to explicitly specify that the enum is a byte

#

its an int by default or a short?

quartz folio
#

why not do that then?

void fog
#

with what they showed for values, no reason not to

swift falcon
void fog
quartz folio
void fog
#

You told us what you want to do... not why

swift falcon
#

ask

void fog
swift falcon
void fog
#

enums under the hood are whole numbers

#

you can just store it as an int

swift falcon
quartz folio
#

You can use generics with enums just fine, there is nothing stopping you

void fog
#

You do realize thats not saying anything, right?

quartz folio
#

just constrain it to Enum if you care to do that

swift falcon
swift falcon
quartz folio
void fog
#
[Serializable]
public struct Something<T> where T : enum // or whatever needed
{
    [SerializeField] private bool _isDay;
    [SerializeField] private T _value;

    public bool TryGetDay(out Day day)
    {
        day = _value;
        return _isDay;
    }
    
    public bool TryGetMonth(out Month month)
    {
        month = _value;
        return !_isDay;
    }
}```
#

that would need some rework... those trys would fail in various conditions lol

swift falcon
# quartz folio what does that mean?

if you're referencing a day as a serialized field.. the inspector will give you a dropdown that shows the choices ...
I want to make the inspector show a dropdown that has 2 data types either a month or a day

void fog
#

Type[] types = new(){typeof(Day),typeof(Month)};

craggy veldt
#

all he needs is a custom editor, really

quartz folio
#

What was wrong with what I previously provided? You can easily make a property drawer that displays that struct that way

latent latch
#

Or if you wanna experiment using serializereferences

swift falcon
swift falcon
#

thank you all and sorry for confusing you

latent latch
#

There's this too, but it doesnt support generics, you'd have to box your enum in custom classes

thin aurora
thin aurora
#

I know, doesn't hurt to give the solution, does it?

quartz folio
#

Enum is a valid constraint

swift falcon
#

again everyone sorry for confusing you

void fog
thin aurora
quartz folio
#

yes

thin aurora
#

Oh it's been supported since c# 8

#

Alright, then that works ๐Ÿ˜„

craggy veldt
#

since c# 7 we can do that yeah
this is valid public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum

#

in the old days we'd do it like this where T : struct, IConvertible

void fog
#

dbase/foxpro loved their enums

quartz folio
#

I also have a SerializeReference dropdown that supports property drawers and UIToolkit https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown
But if this is the answer to the question it's the most poorly phrased question of all time. It would have been so quick if we got like any code explaining the use case that wasn't relating to the original enum question

thin aurora
void fog
#

struct, IComparable, IConvertible, IFormattable

latent latch
quartz folio
orchid bane
#

When I create GameObjects with GameObject.CreatePrimitive in play mode they persist after exiting play mode, why?

quartz folio
quartz folio
orchid bane
#

No

#

But the class has [ExecuteInEditMode]

quartz folio
#

Well there you go.

orchid bane
#

๐Ÿ˜ 

meager locust
#

How can see more variables if I activate a boolean in the inspector? i see this practice in another script. You put the boolean true and new variables see in inspector

thick bough
#

I've only used OdinInspector for this, just a matter of adding [ShowIf(variable)]. It probably wouldn't be too hard to make a custom inspector with that functionality

meager locust
#

OdinInspector it's a asset?

thick bough
#

Yes

latent latch
#

Free and has a showif attirbute

meager locust
#

thank you

mellow seal
#

As you see in the video if i move the mouse fast its aiming correctly but if i move mouse slowly its not aiming.
How can i fix that?
https://www.youtube.com/watch?v=IlulWcTnn9Y&embeds_euri=https%3A%2F%2Fforum.unity.com%2F&source_ve_path=MjM4NTE&feature=emb_title
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using StarterAssets;

public class Aim : MonoBehaviour
{
StarterAssetsInputs starterAssetsInputs;
[SerializeField] private LayerMask layerMask;

[SerializeField] private GameObject debugObject;

private void Start()
{
    starterAssetsInputs = GetComponent<StarterAssetsInputs>();
}
private void Update()
{
    Vector3 mouseWorldPosition = Vector3.zero;

    Vector2 screenCenterPoint = new Vector2(Screen.width / 2, Screen.height / 2);
    Ray ray = Camera.main.ScreenPointToRay(screenCenterPoint);
    if (Physics.Raycast(ray, out RaycastHit raycastHit, 999f, layerMask))
    {
        debugObject.transform.position = raycastHit.point;
        mouseWorldPosition = raycastHit.point;
    }

    Vector3 worldAimTarget = mouseWorldPosition;
    worldAimTarget.y = transform.position.y;
    Vector3 aimDirection = (worldAimTarget - transform.position).normalized;

    transform.forward = Vector3.Lerp(transform.forward, aimDirection, Time.deltaTime * 40);
}

}
`

mellow seal
#

what is that mean

#

there is debug raycast in the video if you are talking about that

main shuttle
#

No the GIF explains how you actually post code here in a code box with colours.

mellow seal
#

oh okey i didnt know that thanks
let me try rotatetowards 1 second

main shuttle
#

You can also read !code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

mellow seal
#

@main shuttle sadly still same problem

    private void Update()
    {
        Vector3 mouseWorldPosition = Vector3.zero;

        Vector2 screenCenterPoint = new Vector2(Screen.width / 2, Screen.height / 2);
        ray = cam.ScreenPointToRay(screenCenterPoint);
        if (Physics.Raycast(ray, out RaycastHit raycastHit, Mathf.Infinity, layerMask))
        {
            debugObject.transform.position = raycastHit.point;
            mouseWorldPosition = raycastHit.point;
        }

        Vector3 worldAimTarget = mouseWorldPosition;
        worldAimTarget.y = transform.position.y;
        Vector3 aimDirection = (worldAimTarget - transform.position).normalized;

        Vector3 newDirection = Vector3.RotateTowards(transform.forward, aimDirection, 40*Time.deltaTime, 0.0f);

        transform.rotation = Quaternion.LookRotation(newDirection);
    }
}
still mica
#

how do i access the effects with a script

main shuttle
#

If that's the case, it's not the smoothing that's the problem, it's the aimDirection that's the problem.

main shuttle
#

Or the URP one, you can look that up yourself.

still mica
#

oh it's TryGet

#

thanks

orchid bane
#

What networking framework is more reliable in terms of count of job offerings? Photon or mirror?

deft timber
#

hey so i'm using addressables, and im releasing the loaded assets by Addressables.ReleaseInstance(), they are deleted from the hierarchy, tho the ref count in the profiler is stll 1 and the memory isn't released, why is that?

muted zealot
#

Hey guys, does anyone know if it's possible to query your project settings in scripts?
For example could I check the company name in the player settings?

main shuttle
fiery saddle
#

Iam using UniTask and with it iam trying to delay action, however if object is destroyed, how would i kill that task?

I tried creating function asnyc UniTask DespawnTimer but how do i kill that returned task?

golden vessel
#

If I store an IEnumerator, does it becomes null when the coroutine finishes?

jaunty needle
#

I still have this issue guys, my triangle isn't being drawn

#

Here is the full script:

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class ProcGrid : MonoBehaviour
{
    public int xSize, ySize;
    Vector3[] vertices;
    private Mesh mesh;

    private void Awake()
    {
        StartCoroutine(Generate());
    }

    private IEnumerator Generate()
    {
        WaitForSeconds wait = new WaitForSeconds(0.01f);

        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Procedural Mesh";

        vertices = new Vector3[(xSize + 1) * (ySize + 1)];
        for (int i = 0, y = 0; y <= ySize; y++)
        {
            for (int x = 0; x <= xSize; x++, i++)
            {
                vertices[i] = new Vector3(x, y);
                yield return wait;
            }
        }


        mesh.vertices = vertices;

        int[] triangles = new int[3];
        triangles[0] = 0;
        triangles[1] = xSize + 1;
        triangles[2] = 1;

        mesh.triangles = triangles;

        

    }

    private void OnDrawGizmos()
    {    
        if(vertices == null)
        {
            return;
        }

        Gizmos.color = Color.black;
        for (int i = 0; i < vertices.Length; i++)
        {
            Gizmos.DrawSphere(vertices[i], 0.1f);
        }
    }
}
#

And screenshots:

#

Please someone help

hollow stone
#

You can also go into wireframe rendering mode and see if you see the edges

jaunty needle
#

thank you, finally

zinc citrus
#

Hi guys I have a problem , I download I asset bundle that it's a scriptable object with photos , text audio, all this works fine except the instiatiate for Android , in pc it works correctly if I make it instiatiate from start for testing in the correct place , why I doesn't work for the phone ?!

rotund burrow
#

how would OnCollisionStay method work if there are collisions with multiple objects at once? if i want to know if there is a collision with certain gameobject, do i have to make a list and update it on collision enter and exit?

thin aurora
#

My guess is that it is invoked multiple times per frame for each object

lime grove
#

โ„ข

#

Alt+0153. ^_^

rocky laurel
#

weight painting is the way to fix this issue, but since im a programmer, not a 3d artist, i have never touched blender in my life, can someone pls help

#

if needed, i can send you the model if you need information

crisp minnow
#

Vector Math question, need a bit of help on how to actually reason this out:

I have two objects on a board (made of grids), there is one instance that if one pieces moves into another that's staying still, a **shove ** would happen to the stationary piece.

So say the piece getting shoved is at (1,0,2) and the shover is at (1,0,1) - aka just below him, he would shove the piece to (1,0,3). The issue is that all pieces have a Rotation Quaternion to them. Suppose the shoved piece is looking to the right, it would therefore be shoved to its left. I'm not sure how to translate this in practice.

So in summary I end up with:

  • Global direction of a shove for a given piece - e.g. (0, 0, 1) from example above
  • A Quaternion Rotation (such as Quaternion.Euler(0, 90, 0))

And I'm trying to convert the global direction above to the local movement for the piece, which in this case would be (-1, 0, 0). What operations would I need to accomplish this?

#

To add to the above, I tried using the omnicalculator, and when plugging in vector to be rotated as (0,0,1), around Y axis of rotation for a 90 degree turn, I ended up with the opposite result (1,0,0) instead of (-1,0,0). I'm also not sure what operation it did to acquire that result, however. Image below.

#

I'm assuming that what I'm doing is a local to global translation in this case, so maybe negating the answer would get the global to local instead?

silk girder
#

hey there! does anyone know how AssetBundle.LoadFromMemoryAsync works? The description in the documentation is quite complicated

rocky laurel
#

weight painting is the way to fix this issue, but since im a programmer, not a 3d artist, i have never touched blender in my life, can someone pls help
if needed, i can send you the model if you need information

polar marten
silk girder
#

my friend gave me his game bcoz he stopped working on it

#

so im trying to understand how it works

crisp minnow
#
        private void RunDumbTests()
        {
            Debug.Log("RUN DUMB TESTS IS ENABLED! Disable it unless you're feeling DUMB!");

            List<Tuple<Vector3, Vector3>> list = new List<Tuple<Vector3, Vector3>>()
            {
                new Tuple<Vector3, Vector3>(new Vector3(1,0,1), new Vector3(1,0,2)),
                new Tuple<Vector3, Vector3>(new Vector3(1,0,1), new Vector3(1,0,2)),
                new Tuple<Vector3, Vector3>(new Vector3(1,0,1), new Vector3(1,0,2)),
            };

            foreach (var tuple in list)
            {
                var bumper = tuple.Item1;
                var victim = tuple.Item2;
                var globalDir = victim - bumper;
                var victimRot = Quaternion.Euler(0, 90, 0); // right
                var localResult = victimRot * globalDir ;
                var invertedLocal = -localResult;
                Debug.Log($"Tried bumping from {bumper} to victim at {victim} with global dir {globalDir}" +
                          $". For a right turn we got {localResult}.  Inverted it: {invertedLocal}");
            }
        }

When in doubt try it out, just need to plug in some example coordinates maybe I can learn from trial and error. Appreciate anyone with Quaternion knowledge to weigh in however ๐Ÿ™‚

polar marten
#

before you say anything more

#

look at the documentation for InverseTransformDirection

crisp minnow
#

Might be worth checking out their implementation, thanks pangloss. I don't have access to transform, so will have to see if it's simple enough to do it myself (not using game objects for any of these due to network traffic)

#

Although I'm hoping I'm on the right track already with this and it's a trivial mathematical calculation.

polar marten
#

do you have a screenshot of your game

crisp minnow
#

It's not much to look at, I kept telling the artists to not get involved for now ๐Ÿ˜›

#

This is what I'm working with for the time being. Getting them to move and collide (shoved etc) correctly

#

This is a renderer element that takes a resulting board and generates game objects for it

polar marten
crisp minnow
#

all computations happen server side, the hope would be they don't get coupled up with Unity, and so far has been relatively simple to find unity alternatives

deft timber
#

to load/unload things dynamically?

#

any recommendations?

polar marten
#

what is the game

deft timber
#

im having a sequences of enemies

#

each esequence has like a pack of enemies

polar marten
#

okay, right away

#

i can stop you there

#

you do not have to memory manage this manually at all

deft timber
#

after the sequence ends, i want to load the next one and unload the previous one

polar marten
#

you don't need to worry about the resource usage of this

deft timber
#

i do need to wory about that

polar marten
#

why

deft timber
#

switch has limits of 3gb of ram

#

and right now it doesn't open on switch cuz of ram exceed

polar marten
#

have you run a memory profiler on a standalone build

deft timber
#

yes i did

polar marten
#

and what did it say?

deft timber
#

like i stated, it's not releasing the memory after doign Addressables.ReleaseInstance()

polar marten
#

no

#

i'm asking what is using memory

#

according to the Memory Profiler

deft timber
#

the enemies textures and animations

polar marten
#

the textures

#

and how did you compress them?

deft timber
#

also frmo previous (unloaded) sequences

polar marten
#

what size are they?

#

the issue is your texture settings

#

it always is in similar situations*

deft timber
#

i have it like that mostly

polar marten
#

okay

#

you omitted the most important part

#

take a screenshot of the whole inspector, so that it shows (near the bottom) the actual selection of compression settings

deft timber
#

here you go

polar marten
#

you have to pull open the bottom drawer

#

where it says the name of the image

#

also, the Switch module is not installed

deft timber
#

im not on switch branch right now

polar marten
#

okay

deft timber
#

the compression method is set to Normal quality

urban steeple
#

Ive got an object with a cloth simulation (think a sheet of paper) when i shoot it holes are instantiated onto the surface. The issue is when i then move the cloth the holes remain where they were instantiated. How can i like attatch them to the cloth?

deft timber
#

should i override the compression method for switch?

polar marten
#

i agree it's confusing - it's where it says zamykanie oczu... at the bottom, at the bars

#

pull that up

deft timber
polar marten
#

okay

#

do you see now what it is telling you?

deft timber
#

yea idk why the texture is 10.5mb

#

when the png file is like 250kb

polar marten
#

okay

#

well you're at the start of a long journey

#

multiple journeys

deft timber
#

on switch branch i have a switch icon down there

#

should i override the compresion ?

#

to none or something?

polar marten
#

well

#

what is your goal? to port a pre-existing game to the switch?

crystal vale
polar marten
#

is it a visual novel?

deft timber
#

it it a shooter 2D

urban steeple
polar marten
#

cool

urban steeple
deft timber
#

when i did the profiling, the memory used was like 3.4GB which almost 50% of it was the textures

#

even tho i unloaded the sequence (with the textures)

polar marten
deft timber
#

so they should release the memory

polar marten
#

shouldn't there be like, the content of a terrain background or something in there?

thin aurora
deft timber
#

it is player death's animation frame

#

when he's closing his eyes

polar marten
#

okay

deft timber
#

i just wanted to show you the texture settings, dont mind that

polar marten
#

and is this a pixel art game?

deft timber
#

no

urban steeple
deft timber
#

i'd love to show you more unforunately i cannot due to NDA

thin aurora
urban steeple
polar marten
#

because you're going to release the game and everyone's going to see the art anyway

thin aurora
deft timber
#

what are the things i can solve "right away" as you stated?

polar marten
#

all you gotta do is google texture compression unity! a lot of these problems are easy to solve @deft timber

#

you will just learn what those import settings mean

deft timber
#

alright i'll start from there

polar marten
#

that will be the first step on the expanding brain meme

urban steeple
polar marten
#

the second is realizing that the file format has nothing to do with the size in memory

thin aurora
#

You got the initial position, though

#

Can't you find the relative position and update it?

polar marten
#

unity doesn't deliver a PNG in the player build

#

the fact that it's a PNG is meaningless

deft timber
polar marten
#

i think it's going to be fine

deft timber
#

a stone, which the enemies throw at you = 3milion tris

polar marten
#

it sounds like right now you are doing tech art

deft timber
#

but ofc we reduced it to 1k

thin aurora
#

Cloth sim positioning goes over my head so I can't really answer it

polar marten
#

this is a 3d game?

deft timber
#

it is a 3d game with 2D view

polar marten
#

or you mean 2.5d with 3d assets

#

gotchyu

deft timber
#

but the assets and models are 3d indeed

polar marten
#

you should really aggressively search "Tech art for unity" and different tutorials for importing assets

crisp minnow
# polar marten look at the documentation for `InverseTransformDirection`

Wasn't able to find their implementation, but by their own explanation it appears to be a simple inversion (negate everything) on the resulting Vector3. Having tested a few different inputs it looks like that's all I need - negate the result I got since I'm going from global to local, not the other way around! Cheers ๐Ÿ™‚

polar marten
#

and see all the little details involved

#

it sounds like you already know a lot so don't sweat it

deft timber
#

so it could solve the exceesing RAM usage problem?

#

where the textures takes roughly up to 50% of the used memory?

polar marten
#

well that's what your profiler says

#

that it's the textures

#

yeah

deft timber
#

okay

polar marten
#

because they are uncompressed and full resolution

#

an eye closing animation, for example, probably only needs to be 128x128 max size, and you can compress it

#

it might even look better slightly blurred

deft timber
#

well ig i can just leave them full res on pc (maybe future steam development?)

#

and override it on switch

polar marten
#

the switch has whatever, a 720p display

#

you shouldn't have a single switch texture above 1024x1024

#

but you also need to atlas, you need to set compression settings

deft timber
#

got ya

polar marten
#

the thing like the eye animation, it's 2 colors

#

so it can be stored differently

#

also in texture import settings

#

but now that you see that drawer, you know how large this stuff is

deft timber
#

yea it's our first product on switch, we're still learning

polar marten
#

you can also use the build report tools to see how things are shipped

#

yes don't sweat it

deft timber
#

it's a hard one ngl, xbox is much easier ๐Ÿ˜„

polar marten
#

but at least you're out of the hellhole of Addressables

deft timber
#

yea they doesn't work like we expected it

polar marten
deft timber
#

thank you for your time, wish you all the best

crisp minnow
#

What doesn't make sense specifically?

polar marten
#

you can build a Matrix4x4 instance and it has many of the same methods

polar marten
crisp minnow
#

It isn't

polar marten
#

like the specific thing you are trying to do

crisp minnow
#

Movement / collisions will happen on the server, no rendering takes place

polar marten
#

it's hard to succinctly say how wrong this all sounds

polar marten
#

the moment you said collisions

crisp minnow
#

It's not physics based, it's discrete collisions

polar marten
#

it looks like you move pieces around

#

i don't know what the game is

crisp minnow
#

There are predefined rules to how things can play out

#

Yes of course, I don't blame you for that. I think it would have been much to pitch a whole game to solve a minor issue ๐Ÿ˜›

polar marten
#

is this a minor issue? the whole architecture sounds wrong

crisp minnow
#

Does it? I never even mentioned the architecture though?

polar marten
#

it sounds like it's a game where pieces move around a board, like a tactical combat game or similar

#

if i were building this networked, i would communicate the state of the game for the sake of simplicity, or differences in the state in the game, and a difference in the position of a piece would not be the relative change since the last state, but a "overwrite"

crisp minnow
#

Server has a board and pieces it updates, it calculates and sends results to all clients which render them via animations or teleports (to catch up on background progress) where they are / end-up

#

Yeah it is a full overwrite

polar marten
#

then it would always be a world space position

#

and the concern of animating between two world space positions would be rendering, and that would permit you to use a transform

crisp minnow
#

Sure but I was asking about an implementation for server side collision resolution

polar marten
#

you are saying server side collision resolution, which makes no sense to me

crisp minnow
#

Sure it does. clients don't decide how they collide. Server does

polar marten
#

you are using a physics word, collision, then you say it's not physics

crisp minnow
#

They can insist all they want ๐Ÿ˜„

#

As in not physics simulation. It's not a unity collision trigger

#

just a collision of pieces moving to the same square

polar marten
#

like i said, rendering the results of that is a rendering concern, you'd have transform

#

it doesn't really matter where the rules are resolved

#

you can communicate the world (or local) space positions of the rules, it doesn' tmatter

#

visualizing it you're doing on the client

#

it sounds like you are struggling with maybe resolving that rule?

#

and you're storing the orientation of a piece as a quaternion

#

which seems bad

#

you can store its transform.forward instead. then this will be very easy for you to achieve

#

quaternions are rendering tools...

crisp minnow
#

transform is unity specific

polar marten
#

well if you're trying to resolve the rules of how the piece is bumped

#

i think you store the rotation as a vector3 direction where it is looking

#

and your problem is solved

#

it can even be a vector2int.

crisp minnow
#

Pieces can rise and fall on the board

polar marten
#

i can tell you think saving space on these types over the network is going to matter - it won't

#

okay well

#

i don't know, what's your goal? use Matrix4x4

#

it has all the methods for this

#

go for it

crisp minnow
#

For what advantage specifically?

late lion
#

I don't understand why the rotation of a piece determines where it gets shoved. Isn't it just based on the relative position of the shover?

crisp minnow
#

Could be worth pursuing if there's a useful benefit

polar marten
crisp minnow
#

it is, but all pieces move based on primitive behaviors (can be a rotation, a cardinal movement and other special behaviors they can carry out on the board)

#

so when a piece gets shoved, it will own that behavior as part of its primitive set. Which it will then execute in sync with all other pieces

polar marten
#

and the wisdom of recreating unity in a headless backend... is limited

#

it sounds like you are a lot more interested in the networking science of all of this

crisp minnow
#

Well, I think this has gone a bit beyond being critically helpful. Thanks for the inverse transform. I'm not exactly planning a redesign of architecture on a prototype

polar marten
#

i'm not sure if there's any value in trying to recreate a scene graph in pure c# on a headless backend server

#

if it were a prototype, you'd be making this a local multiplayer game

#

and use the unity rules as is

crisp minnow
#

it is currently lol

polar marten
#

then why are you networking anything

crisp minnow
#

it's not yet

polar marten
#

i see

#

i think there are a lot of surprises and confusions here. it's hard to give good advice without seeing more of the code. you can look at Matrix4x4

low halo
#

Help im a newbie and dumb

crisp minnow
polar marten
#

before you say anything more, look at it.

crisp minnow
#

lol

low halo
swift falcon
leaden ice
vestal geode
#

This is not usually the newbie channel

#

So you may get less detailed advice

swift falcon
leaden ice
swift falcon
#

holy shit

#

the hell is this

swift falcon
#

its there

#

I sent you

leaden ice
#

this is Visual Studio

swift falcon
leaden ice
#

now fix those compile errors

#

and make sure your class names match your filenames

#

because EventManager and NewBehaviourScript do not match.

#

those errors in particular seem to be that you have two scripts with class NewBehaviourScript

swift falcon
#

damn

#

but It says I have 8 errors in visual studios but nothing is highlighted in red

plucky inlet
#

Hey everyone, I need some thinking help about trigonometry and scrollview scripts... I am using this extension script here https://gist.github.com/yasirkula/75ca350fb83ddcc1558d33a8ecf1483f to center the scrollview to a specific child. This is working perfectly. But as my map will also rotate, I get some weird offsetting from this script. I was trying to add the rotation with a vector but I cant really see a pattern and not even sure, I am using the correct setup of scripts and recttransforms right now. This code is just prototype code, so do not worry about structure ๐Ÿ˜‰ This is what I am using right now scriptwise: https://hatebin.com/epellljqgw

swift falcon
#

lol wtf

plucky inlet
#

you should at first not work with the default script name of NewBehavourScript

swift falcon
#

its not NewBehaviorScript

leaden ice
swift falcon
#

lol

leaden ice
#

as per your error message

swift falcon
#

but what does that have to do with my script having an error

leaden ice
swift falcon
#

oh wow

leaden ice
#

The compiled results of all the scripts go into one file called an "assembly"

#

if there are broken scripts the assembly cannot be built

polar marten
#

formerly ray wenderlich

#

they are written you will thrive

swift falcon
#

btw has anyone here done world streaming?

#

Does anyone know why the Instantiate Map Objects is not appearing?

#

like in the tutorial

lime grove
swift falcon
swift falcon
#

but in visual studio it shows 8 errors but its weird because it says 0 issues found

lime grove
#

Yeah, those errors will be why it's not working.

swift falcon
#

fk

#

but why is nothing highlighted

mellow sigil
#

Are those errors in the file that you have currently open?

swift falcon
#

yep

lime grove
#

I'm not sure if this causes errors or not, but you've put the script in a folder called Editor, yes?

swift falcon
#

na

#

its in here

mellow sigil
#

This is MapDataInspector.cs?

swift falcon
#

yep

lime grove
#

Custom inspector scripts need to be in a folder called Editor.

swift falcon
#

why

lime grove
#

Because they do.

#

That's just how it works.

swift falcon
#

like this basically

lime grove
#

I think the script has to be in the root Editor folder, you can't have subfolders in it.

#

I may be wrong on that.

south steeple
#

Hello, i have a procedural generated map using corridors & rooms linked together, what would be the best way to optimize the performances plz ? i currently have a big box collider trigger in each rooms / corridors prefabs and when i enter inside the trigger, the room/corridor loads, and unload when i exit the trigger. But i don't know if that's the best way to do

swift falcon
#

AssetDatabase giving me an error

lime grove
thin aurora
# swift falcon

AssetDatabase is part of the UnityEditor namespace. Did you add that?

#

I should note that this code will not run in a build application. Are you aware of that?

lime grove
#

Good point.

leaden ice
leaden ice
#

you postesd is the wrong place

frail fjord
#

so much channels

#

sorry

solemn raven
#

hey,
are all classes convertible to UnityEngine.Object ?
is it possible to convert a customClass to UnityEngine.Object ?

frail fjord
#

but you meen my message

#

or quiestion

leaden ice
#

Custom MonoBehaviours and ScriptableObjects are UnityEngine.Object

solemn raven
glossy basin
#

Hello there, this is kinda a beginer question I guess, how can I retrieve the vertices of a mesh only if they dont have the same position as another vertex?

lime grove
#

What are you retrieving them into?

leaden ice
glossy basin
glossy basin
leaden ice
lime grove
#

Like Praetor said then. Check them against the vertices already stored, and if the position matches any of them continue.

glossy basin
lime grove
leaden ice
lime grove
#

Like "if there isn't already a node here, make one".

charred flax
hexed pecan
#

Could you use a shader instead?

#

AFAIK you need isReadable to modify the file itself

glossy basin
lime grove
leaden ice
hexed pecan
#

With a HashSet you wouldnt have to loop anyway

charred flax
leaden ice
#

HashSet would be easy but it will also only work for identical vertices and not close vertices

glossy basin
glossy basin
#

Hold on I will send a picture to better understand

hexed pecan
glossy basin
#

So, my code currently does this

#

it spawns nodes over the vertices of a mesh, since this is a cube, it should have 8 nodes, right?

#

4 on top 4 on bottom or from which side you want to look it from

lime grove
#

One at each corner, basically.

glossy basin
glad tusk
#

I have some code that continuously writes to a texture, but has no need to read from it. I use a coroutine that updates a fixed % of pixels, then updates the texture and waits for the next frame. Itโ€™s still quite slow and was hoping to get general ideas on how I can more efficiently approach this problem

glossy basin
#

but my code instead of spawning 8, it spawns 24 because of 6 faces having 4 vertices (as I understand, unity mesh.vertices algorithim reads faces too, so since there are 6 faces and each face has 4 vertices, it reads 24 vertices in total)

leaden ice
glossy basin
#

its a complex shape

leaden ice
#

OK - I'd look into convex hulls then ๐Ÿ˜›

#

unless you need your hull to be concave...

glossy basin
leaden ice
#

so what are these nodes for

hexed pecan
#

You could toss your code here though so I can see if theres anything to optimize

glad tusk
#

Let me upload it one sec, thank you ๐Ÿ™‚

glossy basin
#

Sorry, Im really bad at loop math, so I cant quite figure out how to do it myself ๐Ÿ˜‚

glad tusk
#
IEnumerator UpdateCloudMap()
{
    yield return new WaitForSeconds(0.1f);
    const int _cloudRes = 344;
    Texture2D _clouds = new(_cloudRes, _cloudRes);
    DigitalRuby.WeatherMaker.WeatherMakerFullScreenCloudsScript.Instance.WeatherMapOverride = _clouds;

    while (true)
    {
        for (int j = 0; j < _cloudRes * _cloudRes; j++)
        {
            float maxIntensity = 0f;

            int x = LehmerRandom.Next((_cloudRes * _cloudRes) - 1);
            int y = x % _cloudRes;
            x = ((x - y) / _cloudRes);

            for (int i = 0; i < _cells.Count; i++)
            {
                // Get tornado position and intensity
                Vector2 tornadoPos = _tornado.GetPosition(i);
                float tornadoInt = Mathf.Clamp01(_tornado.GetCellFraction(i)); // KEY:OFFSET

                // Get (potential) cell texture coordinates
                int cellX = WorldPosToCellPos(CloudPosToWorldPos(x, _cloudRes), tornadoPos.x, _hookPositions[i].x);
                int cellY = WorldPosToCellPos(CloudPosToWorldPos(y, _cloudRes), tornadoPos.y, _hookPositions[i].y);

                if (cellX < 0 || cellY < 0 || cellX > _cellSize || cellY > _cellSize)
                {
                    continue;
                }

                float cellVal = Math.Max(0, _cells[i][cellX, cellY] - (1f - tornadoInt));

                if (cellVal > maxIntensity)
                    maxIntensity = cellVal;
            }

            float cloudInt = Mathf.Clamp01((maxIntensity * 1f) + 0.6f); 

            Color color = new(cloudInt, cloudInt, cloudInt, 1);
            _clouds.SetPixel(x, y, color);

            if (((j + 1) % 1376) == 0)
            {
                _clouds.Apply();
                yield return new WaitForEndOfFrame();
            }
        }

    }
    
}
swift falcon
leaden ice
#

the very first response to your question

glad tusk
#

The Lehmer RNG just allows me to update the pixels in a random order, otherwise there's an obvious "scan line"

#

But without repeats/missing pixels

thin aurora
swift falcon
#

wow

thin aurora
#

So you need to make sure scripts that include it are excluded, or you make sure any editor methods are not compiled, which is also possible but your behaviour must still work, obviously.

swift falcon
#

so im doing this all for nothing basically

thin aurora
#

I'm sure there is another way

leaden ice
harsh bobcat
#

not exactly a coding question but need confirmation. There are 24 unique rotations when rotating on an axis by 90 degrees at a time right?
4 rotations when pointing in a direction times 6 axes is 24 rotations, even though theres 64 combinations of eulerAngles where x y and z are 0, 90, 180 or 270.

leaden ice
#

6 cube faces

#

24 orientations total

hexed pecan
harsh bobcat
leaden ice
# harsh bobcat nice thanks

euler angles cannot be trusted as every orientation can be represented by an infinite number of euler angle sets

glossy basin
harsh bobcat
swift falcon
#

cause I can't find anything on YouTube about it

leaden ice
solemn raven
#

hey,
reorderableList has a call back for Onchange ChangedCallbackDelegate(ReorderableList list); ... I'm not sure how is to use this ? I wanna know how to get which item has been modified and react based on that piece of info

swift falcon
#

this is hurting my brain lol

#

im more of a video tutorial guy

leaden ice
#

Programming in general is a very text based practice

#

you should get used to reading and understanding documentation

swift falcon
#

Would addressables be an alternative to world streaming?

leaden ice
#

Completely orthogonal topics

swift falcon
#

fk

solemn raven
#

hey,
i have some custom properties that was created by custom editor using EditorGUI.PropertyField() it look nice , but I cant edit them in the inspector , is there is a reason for that ?

swift falcon
#

So what's actually the best way

#

that would work in a build

#

very east method instead of creating 10 scripts

leaden ice
#

The best way for what

naive swallow
#

So, I know how to raycast through the camera and find out what your mouse cursor is over, but how would I go about finding out where the mouse would cross a plane at y=0? I want to have a fallback in case there is nothing under the mouse without having an infinite collider across the world at y=0

naive swallow
swift falcon
#

I dont understand RessourceLoad

somber nacelle
#

Resources.Load was suggested to replace your use of AssetDatabase, not the entire world streaming setup you copied from a tutorial

leaden ice
#

and basically does what your AssetDatabase code did

#

but at runtime

#

and is actually simpler than the AssetDatabase code

hexed oak
#

I've successfully tested embedding content within assemblies as well as an additional avenue to use if Resources.Load is not preferred

naive swallow
somber nacelle
#

just create a plane in the code

swift falcon
#

Found this

naive swallow
safe knoll
copper shoal
#

For some reason, my code doesn't run as intended. I wanted to make a point that appears where the raycast hits. It instanciates correctly and updates, but it doesn't get destroyed later. What did I do wrong?

RaycastHit2D hit = Physics2D.Raycast(transform.GetChild(0).transform.position, transform.right, LaserRange);

            if (hit.collider != null)
            {
                    // If the circle instance doesn't exist yet, create it
                    if (circleInstance == null)
                    {
                        circleInstance = Instantiate(circlePrefab);
                    }

                    // Update the position of the circle instance to match the point of contact
                    circleInstance.transform.position = hit.point;
            }
            else
            {
                // If the raycast doesn't hit anything, destroy the circle instance
                if (circleInstance != null)
                {
                    Debug.Log("It should be gone now!");
                    Destroy(circleInstance);
                    circleInstance = null;
                }
            }

I don't even see the log message

naive swallow
lime grove
copper shoal
#

Hmm, I added Debug.Log(hit.collider.gameObject.name); after raycast and it sends me the message that it is null.
In Debug tab I can see, that circleInstance is not empty and has a gameObject

naive swallow
#

If you get a log, then the else is running. If you get a log, but it's blank, then circleInstance is null

copper shoal
#

Weird, because it works perfectly now. I moved the first log I mentioned to execute after if and added the second log in else as you said.

#

Anyway, thanks for the help. It's working now

simple egret
#

Yeah it works because if the log was this here: Debug.Log(hit.collider.gameObject.name);, and the raycast didn't hit, it would throw an exception, ending the script execution right there

#

So, not running anything past that line

swift falcon
swift falcon
#

fk

hexed pecan
#

Do you just keep forgetting conversations you recently had

swift falcon
#

ya

copper shoal
#

Is there a way for Raycast to ignore colliders with certain tag?

copper shoal
#

how?

leaden ice
copper shoal
#

Thanks, I used the "Ignore Raycast" layer and it works

swift falcon
#

damn im fked

sacred notch
#

@copper shoal but in theory u can make function with Physics.RaycastAll and u can use tags

leaden ice
copper torrent
#

my b

swift falcon
#

Hey guys does anyone know why the skinned mesh renderer randomly unassigns bones after a frame

#

Im breakpointing my code and i can see clearly the bone has been set

#

But then when i continue it randomly says missing transform on the root bone on the skinned mesh render

#

even though the bone is already there

#
             //Get meshes and bones then copy them to the new mesh
            foreach (var kitsuDnaData in groupedKitsus)
            {
                var p1 = kitsuDnaData.Key;
                var clonedGenZero = p1Instances[p1];
                var config = resourceMap[p1].Config;
                var partsInThisKitsu = kitsuDnaData.Value;

                var meshes = partsInThisKitsu.Select(t => config.Elements.FirstOrDefault(v => v.Key.ToLower() == Part.GetName(t.PartIndex).ToLower()))
                    .Where(t => t != null)
                    .SelectMany(t => clonedGenZero.transform.FindGrandChild(t.TransformName)?.GetComponentsInChildren<SkinnedMeshRenderer>())
                    .Where(t => t != null)
                    .ToList();
                var bones = meshes.Select(t => new
                {
                    Transform = t,
                    RootBoneName = t.rootBone.name,
                    BonesName = t.bones.Select(t => t.name).ToArray()
                }).ToList();

                foreach (var mesh in meshes)
                {
                    var newMesh = Instantiate(mesh.gameObject, go1.transform);
                    newMesh.transform.SetParent(go1.transform);
                    newMesh.name = mesh.name;                   

                    var newMeshRootBone = rootBone.FindGrandChild(mesh.rootBone.name);
                    var newMeshBones = new Transform[mesh.bones.Length];
                    for(int i = 0; i < mesh.bones.Length; i++)
                    {
                        newMeshBones[i] = rootBone.FindGrandChild(mesh.bones[i].name);
                        //newMeshBones[i].position = mesh.bones[i].position;
                        //newMeshBones[i].rotation = mesh.bones[i].rotation;
                        newMeshBones[i].localPosition = mesh.bones[i].localPosition;
                        newMeshBones[i].localRotation = mesh.bones[i].localRotation;
                    }

                    newMeshRootBone.localPosition = mesh.rootBone.localPosition;
                    newMeshRootBone.localRotation = mesh.rootBone.localRotation;


                    var skm = newMesh.GetComponentInChildren<SkinnedMeshRenderer>();
                    skm.localBounds = mesh.localBounds;
                    skm.bones = newMeshBones;
                    skm.rootBone = newMeshRootBone;
                }
            }
#

For a single frame the model is OK hence why i can get a screenshot

#

But no clue why its randomly unassigning the bones

leaden ice
swift falcon
#

Yeah but its not destroyed :S

#

Ill step through the code again

leaden ice
swift falcon
#

im not

#

all im doing is instanting a new model. Taking the skinned mesh renderer and component from that model and adding it to a new one

#

Then im also taking the bones required for that skinned mesh adding them onto the new armature then setting the new skinned mesh renderer with the bones

#

its weird as hell

#

1st frame its fine 2nd frame its all deformed

leaden ice
#

well first off what's FindGrandChild?

swift falcon
#

so yeah this "rootBone" is actually the new armature

#
 /// <summary> Find the first transform grandchild with this name inside this transform</summary>
    public static Transform FindGrandChild(this Transform aParent, string aName)
    {
        var result = aParent.ChildContainsName(aName);

        if (result != null) return result;

        foreach (Transform child in aParent)
        {
            result = child.FindGrandChild(aName);
            if (result != null)
                return result;
        }
        return null;
    }


#

Iterates through children

#

why do they make this hard to do world stremaing damn

leaden ice
#

It is going to be hard

#

nobody "made it hard". It just is hard.

swift falcon
#

the issue is that also there are not many tutorials on World streaming on YouTube

leaden ice
#

Also again YouTube is not always the best resource.

swift falcon
#

they are either too old or use paid 3rd party ressources from the asset store

leaden ice
#

doubt most of them are too old

hexed pecan
#

What exactly makes you think they are too old

leaden ice
#

they won't be using anything that has changed too much over the years.

swift falcon
#

the one I was watching that was somehow decent was great until the database error

#

so I had to stop

leaden ice
maiden breach
#

@swift falcon World streaming is more appropriate for open-world games. Its overkill for the office space scene you showed. Addressables is probably a better option for you

swift falcon
#

Will that do something like World streaming but without making things disappear and reappear like loading?

tall lagoon
#

@simple egret hey man i couldent figure the last part out r u busy? l ike followed your equation and it snaps perfectly buthow can i get it to go in between the points as well

maiden breach
#

It really depends on how you implement. Based on that screenshot and the details youve shared, Id bundle assets in based upon which room they go in. And depending on proximity load/unload the appropriate assets.

steady thicket
#

Is there an easy way to do something similar to Gizmos.DrawMeshCube that would not draw over everything else? I'm trying to work on my debug visualization for an octree and it tends to devolve into a sea of color since I can see the mesh cubes through objects. Do I need to handle this myself if I need them not drawn over objects they are behind or am I missing an easy way to do this?

lime widget
#

I have a script of a bullet that follows an enemy. If the enemy dies the bullet stops at it's corpse. How can I make the bullet keep it's direction and not stop?

swift falcon
#

unity is bugging out

#

push101rofl even the parent is correct

#

can duplicate naming of components cause a issue?

#

cause i clone bones then rename them to the original clones name, but they are parented to a different parent

tall lagoon
#

Sorry mb

#

i dident mean to ping

void fog
#

each bullet should have a target associated with it so you can check if that monobehavior property indicating death has been set

lime widget
void fog
#

i dont recall exactly what you need (still learning) but instead of that MoveTowards, you basically need to tell it to just move in the direction the bullet is facing as soon as death is detected and then give it momentum

void fog
#

not exactly what you need but should help point you in the right direction

swift falcon
#

When i used DestroyImmediate it worked

lime widget
zinc parrot
#

What would make doing Task.Run(() => Function()) stall the main thread for a bit?

tall lagoon
void fog
bronze rampart
#

what's more readable? or maybe a better question is how would you prefer a colleague write this if it was code you both had to work on? (generally speaking)

result = x > 0 ? "positive" : "non-positive";```

```cs
if (x > 0) {
    result = "positive";
} else {
    result = "non-positive";
}
#

im not used to this operator and if and else just seems like more plain english but one line is so much more concise

hexed pecan
#

It's a preference question indeed. I find the first one more readable, as its a pretty short ternary

lime grove
#

I agree with Osmal.

#

An if statement for that seems like overkill.

ruby compass
bronze rampart
#

ty for the input @hexed pecan @lime grove

humble kraken
#

Can someone help me out with a problem please? I have a unit that can stand, move, attack and cast spells. This is implemented with a state machine. The problem is I want some of my spells and attacks not to interrupt the current state and order.
My current implementation:
Player Controller checks for player input and sends an event with the relevant data
UnitManager switches to the relevant order based on the input (move order, attack order, etc)
Order is calling the necessary state. For example, attack order will check if the unit is in range do the attack. If yes, the unit will attack (attack state called) , if not, it will move in range (move state called) . Order will function until new order is given.
The state is responsible for animation and calling the systems. I am using Animancer to use custom code to call animations. For example, the state will play animation attack and on certain animation time line call for a system that fires a projectile

hollow stone
bronze rampart
#

if I cant do ParticleSystem.main.renderer is there another way to access it from the particle system or do I have to use ParticleSystemRenderer?

solemn raven
#

hey,
I'm trying to replace EditorBuildSettings.scenes with a new list of scenes.

so I made a new list List<EditorBuildSettingsScene> SS = new List<EditorBuildSettingsScene>();
then I added all scenes and i can see them via the following loop

  for (int i = 0; i < ss.Count; i++)
  {
       Debug.Log($"I:({i}) _ path : {ss[i].path} _ Count:{ss.Count} _ enabled: {ss[i].enabled}");    
  }

everything is correct, the right count , the right enabled value with the right path.
then to store it on EditorBuildSettings.scenes and replace the older list i use the following command EditorBuildSettings.scenes = SS.ToArray();
It didnt work! , the list has been rest ( all changes i've made have been returned back )
so i stored it on an array instead and looped throught it EditorBuildSettingsScene[] newArray = SS.ToArray();

  for (int i = 0; i < newArray.Count; i++)
  {
       Debug.Log($"I:({i}) _ path : {newArray[i].path} _ Count:{newArray.Count} _ enabled: {newArray[i].enabled}");
  }

the order is not correct , the enabled value are all true , why ???

earnest gazelle
#

When I scale UI elements and set them to zero, it seems they are not rendered. So, I do not need to set active to false or disable image component?
The visibility is based on the distance to camera. I scale UI elements and finally I want to hide them

ionic adder
earnest gazelle
ionic adder
earnest gazelle
#

I can have two parents, one for active and the other for inactive elements, perfect.

#

ActiveParent
InactiveParent --> canvas group:0 or disabled game object

ionic adder
cold parrot
ionic adder
cold parrot
#

in any case, scaling of UI elements is generally a very bad idea as the whole system is unaware of scale

earnest gazelle
cold parrot
#

you can use it as a temporary effect but should always return to a 1.0 scale as soon as you can

cold parrot
ionic adder
earnest gazelle
#

So, add canvas group for each UI element and just set it to zero or 1

cold parrot
#

yes, its best to just use a canvas group or a nested canvas to control visibility and break the refresh-cascade in well defined places

earnest gazelle
#

Another way is to set the position to another place but I do not prefer it

cold parrot
#

if you need your layoutgroups to respond to the visibility you need to disable to game objects ofc, there is no cheating that

earnest gazelle
#

Set scale to zero is OK because I adjust their scales based on the distance to camera, to hide it set them to zero. I did not get why you say it is a bad idea

#

They are a bunch of world space Icons

#

like gizmo

cold parrot
#

because the ui system does not observe scale as trigger to refresh itself

#

like it does with size

#

and the whole point of a rect transform is to be able to define an arbitrary rect without abusing scale

earnest gazelle
cold parrot
#

however if you do scale your rect transform, and then trigger a layoutgroup, everything goes wonky

earnest gazelle
#

๐Ÿ˜‚

earnest gazelle
#

Why do you assume I use layout?

#

if you mean unity UI layout group component

void basalt
#

Unity/Physx use AABB for collision resolution right? Can someone explain how this works if the box itself never actually rotates?

#

Like if I have a box collider on a cube and I toss it around, obviously it's rotating

#

like how does corner detection work then?

cold parrot
leaden ice
void basalt
#

By "box" you mean the render right?

leaden ice
#

no

#

I mean the box collider

void basalt
#

wat

#

so confused

earnest gazelle
#

It checks AABB first

cold parrot
leaden ice
void basalt
#

oh alright

leaden ice
#

the AABB is like a bigger box that holds the small box of the box collider

#

when the box collider is rotated, the AABB is larger than it - since it can't rotate and has to encompass the whole thing

void basalt
#

So after the quick AABB is done, is separating axis theorem then used to complete the query?

leaden ice
#

So like when the box collider is rotated the AABB will be the larger outer rectangle in the image on the right^

cold parrot
#

depends on what the collision behaviour is expected to do, the AABB lookup is used as a fundamental part of all physics queries

leaden ice
void basalt
#

Ok cool

leaden ice
#

I think there's actually a different implementation for every collider type pair

earnest gazelle
leaden ice
#

so like:
Sphere - Sphere
Sphere - Box
Sphere - Capsule
Box - Box
etc...

cold parrot
earnest gazelle
#

In non convex models, in final check, it tests all faces, right?

earnest gazelle
#

Now, I have just one canvas

cold parrot
#

icon != canvas

earnest gazelle
#

Canvas
parent
icon1
icon2
...

cold parrot
#

is this a 2D or 3D world?

earnest gazelle
#

Like gizmo unity ๐Ÿ˜

#

I do not know how I can explain more

cold parrot
#

in most cases each individual thing (like your icons) in a world UI should be its own canvas

earnest gazelle
#

World space 2D icons in 3d world

cold parrot
#

those should all be individual canvases

earnest gazelle
#

Canvas1
Canvas2
...
?

cold parrot
#

well, if you need them to be canvases for convenience, then yes, if you care about performance, make them simple sprite renderers

earnest gazelle
#

just one drawcall

#

OK, thanks

#

No, sprite renders do not work. They are icons and should be rendered on top like UIs

cold parrot
#

draw-calls aren't the bottleneck with UI

whole gull
#

What is a good way for enemy objects to find the player object? Finding the object from the hierachy seems inefficent and unnecessary, because every enemy instance would have to search for the player themselves, when all they need is a reference. This reference could be provided somehow from somewhere, but how? A static player reference on a static class? That seems dirty.

cold parrot
lime grove
#

GameObject.FindWithTag("Player")

whole gull
# lime grove Use tags.

You mean give the player a "player" tag, then call "FindGameObjectsWithTag" on each enemy instance to find the player? My problem with that is that every individual enemy would call "FindGameObjectsWithTag", even though that shouldn't be necessary.

whole gull
whole gull
#

OK I should add that my player object doesn't exist right away. I place an object which designates a spawn location for the player, the player is then spawned there when the game runs.

whole gull
#

An arena shooter where you spawn and a lot of enemies attack you all at once, nothing special (learning)

lime grove
cold parrot
#

if you care about architecture at all, you'd not use tags, you'd have the enemies register on start with an enemy manager and that enemy manager would inject them with any references they need, same with the player when it spawns, then you'd have a third system that would handle communication between enemy and player manager, i.e. telling the enemy manager that a player spawned which would then tell the enemies

whole gull
#

yes I do very much care about architecture, which is exactly why I ask this question ๐Ÿ™‚

lime grove
#

Enemy manager is a great suggestion then.

whole gull
#

How would the enemies register themselves on an enemy manager?

lime grove
#

Provide a public registration function on the manager script that the enemies can call when created.

swift falcon
#

Just when i wanted to close unity

whole gull
#

which means the enemies need a reference to the enemy manager, so every time I create a scene, I have to put in an enemy manager, and for every enemy I place, I have to drag and drop the enemy manager onto the enemy?

cold parrot
whole gull
#

if the enemy spawner injects it, then the spawner needs a reference, that just moves the problem to a different location, I want to avoid "Find" methods (except they are the standard way of doing things?), I don't want to use singleton pattern for the reason you mentioned

cold parrot
#

essentially having enemy instances saved in the scene breaks clean architecture in some way, you just need to ignore it and use the crummy options you have to resolve that

lime grove
#

You're basically not going to be able to do this without some form of reference in one direction or other, so pick which one you dislike least. ๐Ÿ˜›

cold parrot
whole gull
#

I mean, if I use one of the Find methods, then all of my problems are pretty much solved, I just read and heard here and there that finding objects is expensive and in this case it's kind of unnecessary, but maybe it's the way to go?

cold parrot
#

note that you should only avoid find methods at runtime after scene load. they are fine during init. you'd also never use them as a hack where better patterns exist, for some things however they are the only option

lime grove
solemn raven
#

hey,
how to add item to the bottom of a list ?

cold parrot
#

the problem with find methods, architecturally, is that they couple your enemy implementation to the context they live in, and you want to avoid that as much as you can

lime grove
whole gull
solemn raven
lime grove
#

Didn't you say enemies would be spawning during runtime though?

whole gull
cold parrot
whole gull
lime grove
#

It depends on which solution you decide to go with I guess.

solemn raven
#

i have a list that i want to convert into array , as soon as i loop through it , the order of the items changes

lime grove
cold parrot
cold parrot
solemn raven
#
 List<Custom> newList = new List<Custom>();
        for (int i = 0; i < script.oldList.Count; i++)
        {
            FnTypePi p = script.oldList[i];
            p.enabled = script.oldList[i].enabled;

            newList.Add(p.Settings);
            newList[i] = p.Settings ; // in attempt to keep item with index 0 to be in the newList[0] ... it keeps changing 
        }

after that I'll convert newList to array but this loop is running on the editor and everything is missed up there

#

u are talking about Arrays

#

lists has defined order, correct?

maiden breach
#

They both do.

whole gull
#

both list and array have a defined order

void basalt
#

Can someone explain ECS / Cache friendly designs?

I understand that we're supposed to have a main "entity" and a bunch of components in a data container attached to it, but I'm still having trouble wrapping my head around what this does for the cache.

Is the idea just to have a small base entity, so that it easily fits in the cache? And then always access all entities frequently so they stay in the cache?

lime grove
#

Aren't lists not indexed? I must be misremembering, sorry.

earnest gazelle
solemn raven
#

I honestly just think its the editor, its not as good as the rest of the engine

whole gull
solemn raven
#

what I wrote up there should have been enough to reorder the list correctly

cold parrot
earnest gazelle
solemn raven
earnest gazelle
#

You can keep the player ref on that spawner class, then instantiate enemies and call init method of Enemy mono class and finally pass the player ref to them

whole gull
earnest gazelle
#

It is better than find game object with tag in my view.
If the player is single, probably find gameobject with tag will be OK too

whole gull
#

player is single yeah

hexed pecan
#

A simple static reference could work

whole gull
#

it does! but everyone tells me static classes are bad!

hexed pecan
#

Ask them why

earnest gazelle
#

Then instantiate your enemies in runtime

hexed pecan
earnest gazelle
cold parrot
# void basalt Can someone explain ECS / Cache friendly designs? I understand that we're suppo...

entities arent things, they are just identifiers (a simple int), stuff isnt attached to entities in an OOP/compsition sense, data is attached to entities by making a list of all data objects of a given type and associating that list's entries with entity ids (for example by using a sparse set), the cache friendlyness comes from this: when using that data to process a system, you can iterate through a tightly packed region of memory that ONLY contains the data you need for processing, no extra, superflous data, in consequence, more useful data fits into each cache line which means you need to request fewer pages of memory from RAM.

whole gull
hexed pecan
#

Probably no need for a static class, just a static variable on the player class for example

whole gull
#

Then every script could have a reference to that player script? That is good?

hexed pecan
#

If that's your intended purpose of it (it is) then yes

#

Maybe make it {private set; get;} so that other classes can't modify it

earnest gazelle
earnest gazelle
#

For simple indie games it is completely perfect

whole gull
#

it solves all of my problems, but you are right, the scope is global and people want to avoid that

#

imagine it's not a simple indie game

lime grove
#

The rationale I usually see behind it is that if you end up accidentally modifying the global state from somewhere you didn't mean to, it's a lot harder to troubleshoot when things start going wrong and you forgot where you changed it.

hexed pecan
#

How can anything modify it if its setter is private

cold parrot
lime grove
#

Yeah, I agree with you. I'm just saying what I've seen people say about it. ๐Ÿ˜›

whole gull
cold parrot
solemn raven
cold parrot
#

the intended purpose is to capture the notion of "only one thing of X can exists", the anti-pattern is "give access to everyone, anytime, anywhere"

solemn raven
#

editor is full of bugs

solemn raven
#

its

cold parrot
#

then your code is wrong

#

or your assumptions about the original order are

earnest gazelle
# hexed pecan Why

Because every time you have a global scope class, you finally face big giant God class specially for junior developers.
I have faced in my team, my colleagues

#

It is one of drawbacks

hexed pecan
#

With god class you mean some super game manager that has every reference possible?

solemn raven
earnest gazelle
hexed pecan
#

I dont see the logic here

cold parrot
earnest gazelle
#

Say I change it in the future but wont

hexed pecan
earnest gazelle
hexed pecan
#

We are talking about one static reference to the main player

#

@whole gull Go make your game

whole gull
#

๐Ÿ˜„

swift falcon
#

Is there a way to do a "ConeCast"?

void basalt
cold parrot
swift falcon
#

I wanted to do something that'd detect certain enemies within a cone from my player controller.

#

However, there seems to be no native "ConeCast" function, and I don't think it's possible to have the sphere projected by a SphereCast increase in radius as it's projected further from its origin.

cold parrot
#

it makes sense to gently train oneself to use better patterns so the prototype-think doesn't become too hard to break come production time

cosmic rain
swift falcon
#

Oh wait... ๐Ÿค”

late lion
#

That would be ConeOverlap though

earnest gazelle
cosmic rain
swift falcon
#

... you mean use the SphereCast at maximum size, and then exclude any that don't fall within the correct pitch/yaw from the player?

solemn raven
#

@cold parrot and here is the code I used CustomClass[] newList2 = oldList.Select(it => it.CustomClass).ToArray();

earnest gazelle
cosmic rain
late lion
solemn raven
#

@cold parrot logic wise, there is no reason for editor to mess up my list, but it did , I run this code via editor's button

swift falcon
#

Physics.OverlapSphere, right?

cosmic rain
late lion
swift falcon
#

My apologies.

hexed pecan
earnest gazelle
#

Yes cone cast is meaningless

solemn raven
#

@cold parrot maybe its because ReordableList ?

swift falcon
#

I'm not seeing anything on a ConeOverlap in the scripting manual though...

#

In any case, I'll see what I can do with a series of OverlapSphere calls. ๐Ÿค”

earnest gazelle
#

Radius plus angle view
What about

#

If it is about view range

whole gull
#

I have more questions ๐Ÿ‘€
I'm creating an enemy object, which contains a 3D model of the enemy as a child. This child has an animation controller, which acts as a state machine. I can't figure out the proper object structure for clean code.

  1. My enemy has some stats, like movement speed etc., on which object should these stats live? The root of the enemy?
  2. The states of the animation controller have behaviours, which need to reference the stats. Should these behaviour scripts have a reference to the parent game object (the root)? That seems kind of dirty.
  3. Is a state machine with an animation controller even the way to go when creating an enemy with different states or attack types etc.? (I looked up many tutorials, but it's hard to tell what's outdated and what's still relevant)
hexed pecan
#

DI when spawning the enemies?

late lion
swift falcon
#

I see.

#

So I could use a SphereCastAll to do the same thing too... ๐Ÿค”

#

(If not better.)

earnest gazelle
whole gull
#

movement component is on the parent game object, not on the same object as the animator. I could do animator.parent.getComponent, but then I have a very strict object hiearchy

late lion
swift falcon
earnest gazelle
bronze rampart
earnest gazelle
#

Absolutely, I agree, don't depend on hierarchy

whole gull
bronze rampart
whole gull
#

It's not the way I want to go anyway

#

I dont like it

cosmic rain
bronze rampart
odd lotus
#

There's something with an internal package:
Library\PackageCache\com.unity.services.core@1.4.0\Editor\Core\Configuration\ProjectConfigurationBuilder.cs(93,13): error CS0103: The name 'IoUtils' does not exist in the current context
How do I fix this?

whole gull
void basalt
#
    public Vector3    position
    public Quaternion rotation
}

public class EntityNetworkData {
    public Address networkAddress;
    public int     networkIdentifier;
    public int     rudpRecvAck;
    public int     rudpSendAck;
}    

public static class EntitySystem {

    public static List<EntityTransform>   entityTransform   = new List<EntityTransform>();
    public static List<EntityNetworkData> entityNetworkData = new List<EntityNetworkData>();

    public static EntityTransform GetEntityTransform(int entityID) {
        return clientTransform[entityID];
    }

    public static EntityNetworkData GetEntityNetworkData(int entityID) {
        return clientTransform[entityID];
    }
    
}``` So is this basically how ECS works?
swift falcon
hexed pecan
#

@whole gull Just so I catch up, are you using the animator's states for logic?

cosmic rain
bronze rampart
swift falcon
whole gull
cosmic rain
swift falcon
#

Unless you're saying I ought to just do some simple yaw/pitch/distance check to get stuff, I don't see why I shouldn't use a SphereCastAll to fetch the necessary stuff.

hexed pecan
#

@whole gull Oh it inherits Awake from ScriptableObject

#

Not sure if that works how you want

bronze rampart
whole gull
#

I don't have to do it that way, I just found tutorials that told me to use the animation state machine to control enemy behaviour

#

instead of having 10 if statements in my update loop

cosmic rain
bronze rampart
earnest gazelle
hexed pecan
#

And to hook your AI states to your animator states

swift falcon
whole gull
swift falcon
#

Whatever else falls outside of that check gets ignored.

cosmic rain
#

But yes.

swift falcon
#

As in the sphere is at the player's position.

#

And radiates outward from there.

#

So sure, I guess.

#

Awesome. ๐Ÿ˜„

hexed pecan
whole gull
#

yeah I'm kinda gravitating towards that now

earnest gazelle
#

You should separate logic from animations.
For logic, implement your own state machine or use well known packages

hexed pecan
#

Like you would have an abstract State base class for example and then you would have subclasses of that. Each state's logic would be contained within itself

whole gull
bronze rampart
earnest gazelle
cosmic rain
earnest gazelle
#

You can find it

whole gull
cosmic rain
swift falcon
#

Thus the radius stems from that position.

hexed pecan