#archived-code-general

1 messages · Page 69 of 1

tepid river
#

you mean if you freeze the update thread with a yield return new WaitForEndOfFrame?

#

you only suspend your IEnumerator, not the whole update thread

velvet quartz
tepid river
#

you dont and you dont want to

#

it would freeze the whole game

velvet quartz
#

ok sad.

tepid river
#

if you want to stop your object from running code every update call, put a bool and if(myBool) return;

velvet quartz
#

So how can i stop the update for no go further

dim spindle
#

Why do you want to

tepid river
#

just return early.

velvet quartz
#

I want when i disable nav mesh agent obstacle for my AI because i need to wait the next frame for mesh update.

dim spindle
velvet quartz
#

i can't return becuse the code is on function called from update.

#

not on update himself

tepid river
#

while(true) {
;
}
will suspend your update thread 🤡

dim spindle
tepid river
#

yeah the way to go is to only run your function if you really want to.
and not to start suspending things

velvet quartz
earnest gazelle
#

Yes, I mentioned as well. It is vague. Instantiate using CreateInstance or all instantiation (using developers through CreateInstance + in loading scenes by unity)

thin aurora
#

No, Coroutines run in the "background" and the delay will have no impact. That said, are you sure you want to invoke your coroutine in Update? It will invoke each frame.

thin aurora
thin aurora
#

Unless it's not your code? 🤔

velvet quartz
#

guard clause ?

#

class-scoped variable ?

severe marsh
thin aurora
#

You already have a check in there using return;, and you have a variable in your class you can check

#

Seems pretty simple to add another check.

thin aurora
#

The navmesh agent you disable.

viscid briar
#

Hey does anyone know how to encode a string into a bytes array?

rustic ember
#

using System.Text.Encoding

viscid briar
rustic ember
viscid briar
rustic ember
viscid briar
#

fair enough, thanks anyway

graceful egret
#

Is there any way I can hook into an asset duplication event?

I want to change some serialized fields to be a different value when something is duplicated
Ideally I want to have access to the original asset as well as the new one

modest bough
#

apologies for the hissing + clicking, i need to fix my audio filters
So the player character is connected to a central point by a LineRenderer, and I'm trying to get it to wrap around obstacles, which it mostly does well. The issue is that, with small objects, it's not sticking, and is instead triggering the unwrap function. The current implementation I'm using is:

{ropePositions.RemoveAt(ropePositions.Count - 2);}```
where *ropePositions.Count -1* is the player, -2 is the most recent line connection, and -3 is the second most recent. 
So in instances like in the video, where you can raycast to both of the two most recent line segments, it removes the most recent segment. 
My previous solution involved measuring the angle between the three points, but that seems to have caused more issues, making certain points stick too well instead. So I need some way of more accurately telling the line when to come unstuck.
#

oh discord doesnt like mkvs. ill convert it

soft shard
hollow stone
modest bough
hollow stone
#

I would consider moving back the line path and do more casts maybe.

#

You would want to have some minimal size of the object you can use for delta how far back on the path you move.

#

Then you may find that you collide to a new object that you insert in the list instead.

modest bough
#

smaller steps does sound like it'd be useful down the line for simulating a more rope-like behaviour
my next idea was closer to pic but it doesn't feel very adaptable

hollow stone
#

You can also consider doing circle/sphere casts for narrowing it down and not having to do too many casts ( I would do this once I know that a shape has dissapeared).
So I would go for delta back as the red line in my image, and do that for each segment. If that fails to hit, possibly do some bigger sphere/circle cast to see if there are any objects blocking and then narrow it down.

modest bough
#

I'm familiar with deltaTime, but i'm not quite getting what you mean by delta back. like, a percentage of the distance between the two points?

hollow stone
#

Lets say you define your smallest radius of a shape to be size X, then you could go distance X (Half diameter) back on the line to be sure you would not miss a shape to do a cast to see if you have free vision to next point.

modest bough
#

oh i see, that makes sense

rustic ember
#

How can I pass any type of parameter in a method? Is that possible? Something like this: ```cs
public void Method(AnyType _value)
{

}```
vagrant blade
rustic ember
trim schooner
#

I doubt an SO can have scene references

knotty sun
plucky inlet
#

SoundClips and Prefabs are not in Scene Scope while things out of your hierarchy are in scene scope. Your Scriptable Object is a dataset and therefore also not part of the scene per se

#

You want a generic public field for any script, did I get that right?

#

You cant directly serialise a generic to the inspector

#

You could try, as others suggested, to go with the type object or monobehaviour if they are all monos, but they have to share some base class or interface.

modest bough
rustic ember
rain minnow
rustic ember
#

How can I pass something as the Type?

hollow stone
trim schooner
solemn raven
#

hey, which one was it ?
if I wanted to round float to the highiest int/whole number
example.

int objs = 41;
int boxCapacity = 10; 
int boxRequired = 41/10; // this is a float "4.1", right ? ... how to make the result 5 not 4 ?
#

thanks !

modest bough
rustic ember
hollow stone
rustic ember
solemn raven
prime acorn
#

I have a sprite property on a ScriptableObject, I use this sprite as the icon for the object when instantiating it.

Its basically a list entry which is generated like so:

public class FishListEntry : MonoBehaviour
{
    public Sprite FishImage;
    public string FishName;
    public string FishAmount;

    [SerializeField] private Image FishImageField;
    [SerializeField] private TMP_Text FishNameField;
    [SerializeField] private TMP_Text AmountField;

    private void Populate()
    {
        FishImageField.sprite = FishImage.sprite;
        FishNameField.text = FishName;
        AmountField.text = FishAmount;
    }
}```

Now when I try to set the FishImage property it says "NotSupportedException" the code for that looks like this:
```cs
FishListEntry fle = go.GetComponent<FishListEntry>();
fle.FishImage = group.FirstOrDefault().GetComponent<FishController>().fish.Image;

Where the group is a grouping of the individual controllers, and "fish" is the SO holding the information for that specific object

TL;DR:
I have a sprite as a property on an SO, I reference an instance of that SO (not the SO itself) and want the sprite of that instance to be displayed on my image component

severe marsh
solemn raven
rustic ember
#

int / int = int

#

Do this: cs (float)myInt / myInt2

#

This will equal a float

#

That you then can Ceil

coarse herald
solemn raven
spare dove
#

I'm working on a save system for my inventory, and I need to save a list of item (scriptable object) and amounts for each inventory box. Basically I would like to make a dictionary that can take two separete variable as the value, what would be the best way to do this?

solemn raven
#

thanks ❤️

hollow stone
modest bough
prime acorn
#

Where did I say component on SO? Even if thats just nitpicking but I think I clearly stated the sprite is a property on an SO and I want the sprite property from the SO to be applied on an image component

hollow stone
prime acorn
#

No, FishController is a Controller, or in other words, a Behaviour, Fish is the SO, specifically group.FirstOrDefault().GetComponent<FishController>().fish is that SO in question

hollow stone
hollow stone
prime acorn
#

No sprite is a property on fish

#

fish is of type Fish

#

and Fish inherits from SO

hollow stone
#

Right mb.

cobalt wave
#

can we see the FishController code?
cuz at the moment I think it's the fact that Image doesn't exist in fle.FishImage = group.FirstOrDefault().GetComponent<FishController>().fish.Image;

knotty sun
hollow stone
rustic ember
knotty sun
prime acorn
# cobalt wave can we see the FishController code? cuz at the moment I think it's the fact that...
public class FishController : MonoBehaviour
{
    public float speed = 1;
    public bool direction = true;
    public Fish fish;

    // Update is called once per frame
    void Update()
    {
        transform.position = new Vector3(transform.position.x + speed * (direction ? 1 : -1) * Time.deltaTime, transform.position.y, 0);
        gameObject.GetComponent<SpriteRenderer>().flipX = direction;
        if(!direction && transform.position.x < -8)
        {
            direction = true;
        }
        else if(direction && transform.position.x > 8)
        {
            direction = false;
        }
    }
}```
hollow stone
rustic ember
#

What's the most performant way to recast fx. a float as an int?

cobalt wave
prime acorn
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "New Fish", menuName = "ScriptableObject/Fish", order = 1)]
public class Fish : Item
{    
    [SerializeField] private string fishName;
    public string FishName
    {
        get
        {
            return fishName;
        }
        set
        {
            fishName = value;
        }
    }

    [SerializeField] private float size;
    public float Size
    {
        get
        {
            if (size == 0)
            {
                size = Random.Range(minSize, maxSize);
            }
            return size;
        }
    }

    [SerializeField] private float minSize;
    public float MinSize
    {
        get
        {
            return minSize;
        }
        set
        {
            minSize = value;
        }
    }

    [SerializeField] private float maxSize;
    public float MaxSize
    {
        get
        {
            return maxSize;
        }
        set
        {
            maxSize = value;
        }
    }
    [SerializeField] private float speed;
    public float Speed
    {
        get
        {
            return speed;
        }
        set
        {
            speed = value;
        }
    }

    [SerializeField] private float priceMultiplier;
    public float PriceMultiplier
    {
        get
        {
            return priceMultiplier;
        }
        set
        {
            priceMultiplier = value;
        }
    }

    public float ActualPrice
    {
        get
        {
            return SellValue * Size * PriceMultiplier;
        }
    }
    // How likely the fish is to appear once.
    // If fish appears rarity check will be done again until fish once doesnt appear.
    [SerializeField] private float rarity;
    public float Rarity
    {
        get
        {
            return rarity;
        }
        set
        {
            rarity = value;
        }
    }

    [SerializeField] private Vector2 depths;
    public Vector2 Depths
    {
        get
        {
            return depths;
        }
        set
        {
            depths = value;
        }

    }

    [SerializeField] private GameObject prefab; 
    public GameObject Prefab
    {
        get
        {
            return prefab;
        }
        set
        {
            prefab = value;
        }
    }

    [SerializeField] private Sprite image;
    public Sprite Image
    {
        get
        {
            return image;
        }
        set
        {
            image = value;
        }
    }
}

Its just a property nothing more

rustic ember
knotty sun
#

and
void MyMethod(object o) { }
yes

rustic ember
prime acorn
#

I think this is way more interesting then

hollow stone
# prime acorn

SpanFish.65 is the "fle.FishImage = group.FirstOrDefault().GetComponent<FishController>().fish.Image;" line?

cobalt wave
#

interesting

prime acorn
#

SpawnFish.65, yes

rustic ember
polar marten
#

okay just eyeballing this and seeing you have a library, i don't know if this tool can extrude meshes with holes. you also have to choose the right faces

#

it's not Maya

modest bough
polar marten
#

i meant of the actual game so i can get a sense for what it looks like

hollow stone
prime acorn
#

Pls @ mention me in any replies, need to pick up my gf, so I wont miss them when Im back

modest bough
hollow stone
cobalt wave
#

I'm trying to figure it out, but at this point I think the best action is trying to create a single fish (not in a group), and then trying to change only that one fish's sprite to rule out that the error comes from groups.
Then if it's still only a scriptable object error oof I don't know why.
The only thing I would try changing for now is the Image name in the Fish : Item class because unity already has a definition for Image to maybe something like fImage (f for fish) or anything else
@prime acorn

hollow stone
tepid jewel
modest bough
hollow stone
modest bough
#

hmmm... tiny OverlapSphere to find the nearest terrain object and then moving it 0.01 units away?

hollow stone
modest bough
#

just takes the point where the linecast terminated

#

maybe i should make it find the edges so i can physics stuff later tho

rustic ember
#

Is there an easy way to get an element of an enum by using an index? fx. cs public enum PlayerState { Idle, Walking, Falling, Crouching } In this case I want PlayerState[0] to be PlayerState.Idle, PlayerState[1] to be PlayerState.Walking, etc.

#

Is that a thing with enums?

#

Or do I need an instance of it?

hollow stone
# modest bough just takes the point where the linecast terminated

So this might cause issues when you're moving fast etc. One easy way if dealing with squares and circles that are symmetric around their center is to just either have fixed offset from center or apply an offset - since it will always be pointing in the correct normal direction outwards from the edge where you hit. If you're dealing with more complex shapes you would want to find the edge in some way to either look up vertices or do multiple casts.

polar marten
#

what are you trying to do

hollow stone
rustic ember
hollow stone
#

Simply cast it

#

(PlayerState)0

rustic ember
hollow stone
#

Not even sure if you need to cast it, can probably assign directly from integer as it is it's backing type.

dim spindle
#

Why do you want to do this? @rustic ember

#

Just curious

rustic ember
dim spindle
#

Oh

#

Ok

modest bough
# hollow stone So this might cause issues when you're moving fast etc. One easy way if dealing ...

yeah, at one point the player was triggering new segments when they were moving too fast 😄 but yeah i definitely dont want to be going too fast regardless
i'm still only mucking about with basic shapes for now, but i'll plan for complex shapes
i'm sure there's some way to instantiate an empty game object at the point of impact as a child of the pillar or similar, then have the linerenderer track it
alternatively, i might place some premade transforms on the prefabs for my level objects and just check which one is closest to the impact - in the case of the pillar, one for each corner and middle of each vertex should be fine
i'll sleep on it for now cause it's late, but thank you very much, i greatly appreciate the help you have given me today

idle flax
#

Hey, I need help converting a number.
I have a float that ranges between 0-2. I need to convert that float to a number that ranges from 0-100, but reversed. For example, if the float was 2, I want it converted to 0. If it was 0, I want to convert it to 100. How would I do this?

gray thunder
#

math

prime acorn
coarse herald
pastel holly
#

I have quick question, I am trying to make an simple AI that will essentially just be state machine with 3-4 different states.
My idea of state machine is just to have switch case for each state,
But I been looking around and I see people handling their states with use of Animator, making most state transitions on animation end.
Can someone guide me to what best practice/approach would be ?
This is for a enemy that detects player, walks to them and initiates a fight like in dark souls but without complexity.

buoyant crane
idle flax
buoyant crane
#

sorry for so many edits, that should be the last one 🙃

rustic ember
#

I have a script: cs public class CharacterInput : MonoBehaviour { public Vector2 moveInput; public bool jump; }
I then have two other scripts deriving from CharacterInput: cs public class PlayerInput : CharacterInput { KeyCode jumpKey; private void Update() { if (Input.GetKey(jumpKey) { jump = true; } else { jump = false; } } } and cs public class CPUInput : CharacterInput { private void Update() { // Use neural network to calculate input } }
From a third script I want to use GetComponent() ```cs
public class CharacterMovement : MonoBehaviour
{
CharacterInput inputData;

private void Start()
{
inputData = GetComponent<CharacterInput>();
}

private void Update()
{
if (inputData.jump)
{
Debug.Log("Jumped");
}
}
}```
Will GetComponent<CharacterInput>(); return whichever one of the classes PlayerInput and CPUInput it finds attached to the game object? And how can I modify a field that is local to PlayerInput from CharacterMovement?

buoyant crane
fast belfry
tepid river
#

"why the hell does my spaceship keep accelerating downwards, how did i mess up the AI"
yeah the AI just reached its target and went to idle, not zeroing out the gravity any more

buoyant crane
rustic ember
#

Can I start a coroutine by invoking a UnityEvent?

rustic ember
tepid river
#

yes multiplication in general is faster than division, but if its not running a million times per update, dont worry

#

also your compiler will do magic anyways, so without looking at the assembly code, you cant tell whats going on anyways

tepid river
#

the only relevant performance thing is: dont use Math.Pow if you can use x*x

tepid river
#

because its for general exponent calculation and takes much longer

#

like, factor 20 or sth

rustic ember
#

Wow

#

Okay. Good to know. I very rarely use anything exponential anyways

tepid river
#

exponents and square roots are expensive.

bleak thorn
#

Why .main.startColor doesnt works?

rustic ember
bleak thorn
#

but...

rustic ember
#

SpriteRenderer.material.color is of type Color while ParticleSystem.main.startColor is of type ParticleSystem.MinMaxGradient

rustic ember
# bleak thorn this is not a variable
        ParticleSystem parSys = new ParticleSystem();
        SpriteRenderer ren = new SpriteRenderer();
        ParticleSystem.MainModule main = parSys.main;
        main.startColor = ren.material.color;``` This somehow works
#
        ParticleSystem parSys = new ParticleSystem();
        SpriteRenderer ren = new SpriteRenderer();
        parSys.main.startColor = ren.material.color;``` But this doesn't
#

Can someone explain why?

bleak thorn
#

like that?

rustic ember
bleak thorn
#

ooh, thank you :p

rustic ember
#

You're welcome 😊

buoyant crane
rustic ember
buoyant crane
#

i was about to amend that

rustic ember
#

Ahah okay

buoyant crane
#

i’m not sure what it how it would optimize it for doubles

#

but better to assume the compiler knows best

rustic ember
#

Definitely. Saves me the hassle

hybrid flare
#

Assets\TsTubeMove.cs(26,20): error CS1061: 'List<GameObject>' does not contain a definition for 'tranform' and no accessible extension method 'tranform' accepting a first argument of type 'List<GameObject>' could be found (are you missing a using directive or an assembly reference?)

#

help?

buoyant crane
hybrid flare
#

so remove < and >?

buoyant crane
#

no

buoyant crane
hybrid flare
#

i was struggling to add by prefab to the script

#

so was trying a list xD

buoyant crane
hybrid flare
#

one

#

😭

buoyant crane
#

a list is a collection of GameObjects

hybrid flare
#

yea i tried that before and it kept giving a error

#

lemme try again

buoyant crane
hybrid flare
#

Assets\TsTubeMove.cs(26,18): error CS1061: 'GameObject' does not contain a definition for 'tranform' and no accessible extension method 'tranform' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

#

says that

mellow sigil
#

Try spelling "transform" correctly

hybrid flare
#

XD

#

OML

buoyant crane
#

@hybrid flare you should configure your editor so it underlines the errors and helps give potential fixes

#

!ide

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

hybrid flare
#

i tried that idk how to do it

buoyant crane
hybrid flare
#

online

buoyant crane
hybrid flare
#

alright

bleak thorn
#

How to Create Cube Skin save system?

hybrid flare
#

is there a way to pause all code mid game?

#

like if they die or somthing

buoyant crane
hybrid flare
#

ah perfect

solemn raven
#

Hi,
how do I get the key of a directory?

// 
 Dictionary<Car, int> cars = new Dictionary<car, int>();
for(int i = 0; i< cars .Count; i++)
{
   Car _car = cars[i] //??? 
}
simple egret
#

You foreach, as Dictionaries usually don't have int indices

#

Here, you'd need to pass a Car to retrieve the int value bound to it

knotty sun
simple egret
#

If you need the Car from an int, then your Dictionary is backwards, or you're not using it properly

solemn raven
#

@knotty sun @simple egret Thanks a lot ❤️

solemn raven
glad tusk
#

For some reason, my code is generating the same random numbers every time it is run:

float randPosX = Random.Range(-6000f, 6000f);
float randPosY = Random.Range(-6000f, 6000f);

Debug.Log($"Twister {idx} - Random X: {randPosX}  Random Y: {randPosY}");
#

For more context, I start 3 coroutines that each call the same function where the above code is

#

Each coroutine generates a different random X and Y, but it's the same each time I run the game

#
Twister 0 - Random X: -1798.52  Random Y: -1830.727
UnityEngine.Debug:Log (object)
Tornado:GeneratePreSpawnData (int) (at Assets/CustomAssemblies/Twisters/Tornado.cs:248)
TornadoSpawnController:Start () (at Assets/CustomAssemblies/Twisters/TornadoSpawnController.cs:102)

Twister 1 - Random X: -5659.34  Random Y: -73.58789
UnityEngine.Debug:Log (object)
Tornado:GeneratePreSpawnData (int) (at Assets/CustomAssemblies/Twisters/Tornado.cs:248)
TornadoSpawnController:Start () (at Assets/CustomAssemblies/Twisters/TornadoSpawnController.cs:102)

Twister 2 - Random X: 2916.033  Random Y: 991.0547
UnityEngine.Debug:Log (object)
Tornado:GeneratePreSpawnData (int) (at Assets/CustomAssemblies/Twisters/Tornado.cs:248)
TornadoSpawnController:Start () (at Assets/CustomAssemblies/Twisters/TornadoSpawnController.cs:102)

#

If I stop the editor and re-run the game, I will get the same output

cloud smelt
#

Is it possible to get a tile on a tilemap when it is using something other than 0 as a z level?

#

getTile() does not seem to allow this.

prime wagon
#

why is my default sprite doing this?

indigo rampart
#

Anybody got any advice for custom tiles. Say I wanted the player to place a tile, for example a factory tile. Which has a coroutine which basically just does something every X seconds.

So I create a custom tile, but there is no method 'OnTilePlace' or something like that which I can override to start a corouitine? Any ideas?

Is the only option to add the method to the tile and call the method when it gets placed?

example code:
tilemap.SetTile(tile)
tile.StartTimer()

tough storm
#

I want to draw a line in screenspace, is it possible to do that with the line renderer?

visual plinth
#

How can I make a script that when you press a button you go to a new scene

oblique spoke
visual plinth
#

Thanks but I already figured it out!

stuck forum
#

Is it possible to convert a TKey to int? I have a dict that uses an enum as a key and I need to get the element of the enum. Idk if dictionaries store anything in a order as a list or array though

mossy gust
#

hey guys, im trying to code a lazer script where there are 3 parts of the lazer, the top. the bottom, and the main lazer middle, and if you move the bottom, then the middle will rotate/ stretch to always be linked with it, but for some reason, the middle part always rotates 90 degrees and then rotates

#

and the stretching doesnt work

leaden ice
#
int myInt = (int)myEnumValue;```
#

"TKey" doesn't actually mean anything. It's just the name of Dictionary's generic type parameter

leaden ice
mossy gust
#

whats that

stuck forum
# leaden ice If it's an enum you can just cast it to `int`

So if let's say an enum has 3 diff values
Red
Green
Blue

And there is colors associated to each enum, red for red, blue for blue and green for green (let's call this someDict). if i make an array with the same colors in the same order (let's call this someArray), and i would want to compare if they are the same in some function, would it return true?

Compare(someDict((int)Red));

bool Compare(int element)
{
 return someDict[Red] == someArray[element];
}

edit: [] not ()

#

hope this makes any sense, im just experimenting with things atm

leaden ice
#

is someDict a function?

#

is someArray a function?

#

they are written like functions in your example

stuck forum
leaden ice
#

How is it defined?

stuck forum
#

same for SomeArray, a random Color32 array

#

Dictionary<SomeColorEnum, Color32> i would guess where SomeColorEnum is the Enum with the 3 values

leaden ice
#

I think maybe here's the thing you're missing

#
enum Color {
  Red,
  Green,
  Blue
}```
This is implicitly the same as:
```cs
enum Color : int {
  Red = 0,
  Green = 1,
  Blue = 2
}```
#

so this:

bool example = Color.Red == (Color)0;
bool example2 = Color.Green == (Color)1;
bool example3 = (int)Color.Blue == 2;```
#

would all be true

#

enums are basically just a way to add fancy names to numerical values

#

they are stored by default as int, and can easily be converted via casting to and from int with that defined value.

#

By default they are numbered 0, 1, 2, etc... in the order they appear in the enum definition

stuck forum
#

yeah i got all that, but im just wondering how to compare an object in dictionary and an object in an array if one of them uses an Enum as a key and an int as a key, because with arrays i could make so that the second element is Red and it would automatically break then?

#

so i'd have to order things exactly in the same order in the array as the order of the values in the enum in order for it to be correct when comparing or whatever?

leaden ice
#

I don't think the array and dictionary are even relevant here

leaden ice
#

arrays do

stuck forum
#

yea exactly

leaden ice
#

so I'm a bit unclear what you're asking about here

leaden ice
stuck forum
#

if Red is the first value in the enum, would the color red need to be at element 0 in the array?

leaden ice
#

You can put whatever you want in the array

#

Red == 0 though

stuck forum
#

forget the comparison thing, i just took an example

leaden ice
#

You're saying if you want the array to work the same as the dict?

stuck forum
#

lemme think on how to explain this

leaden ice
#

Then whatever you mapped to Color.Red in the dictionary should be the first element in the array, yes.

#

I don't really understand why you would have both a Dictionary and an Array in this situation though

#

what would be the point of having both?

glossy basin
#

hello there, could somebody explain what ,, does in this array

leaden ice
# glossy basin

This is declaring a three dimensional array of int called data

#

Since it's in parentheses I can only assume it's a parameter in a function or something.

#

Similar to float x; < just a data type and a variable name

glossy basin
#

Ohhh I see, is there any other way to initialize the array as 3 dimensional without ,,?

leaden ice
#

no

#

well there's jagged arrays

#

but that's a slightly different things

#

e.g. int[][][]

glossy basin
#

I see

leaden ice
#

that's an array of arrays of arrays of integers

#

similar but not quite the same

glossy basin
#

I want to convert that to a native array for processing in burst, is that possible?

leaden ice
#

Yes

#

just flatten it

#

all multidimensional arrays can be flattened to a 1D array

#

Then you just do a little math with the / and % operators to convert your 3D index to a 1D index

stuck forum
# leaden ice what would be the point of having both?

Because I made a menu manager system that basically switches between GameObjects (stored in an array) and it switches to the menu corresponding to the index I pass in the menu switching method. I was thinking of using this method generically so if I were to have for instance a pause menu or a main menu, I'd use it there. It has a constructor so it knows what menus are in it

I have, however, a method in a different class that takes in a GameMode enum which does different things (gets called by buttons), but should also show the right game mode settings menu (for customizing a match). problem is the enum/int problem I have right now since I am taking in an enum but it needs an int to switch menus. so I just made a dictionary with the same key (GameMode enum) that stores these menu objects and I just need to switch to the right menu corresponding to the selected game mode

glossy basin
lunar forum
#

So, if I have a singleton script, do I need to attach it to a game object and have it in my scene? It keeps telling me that I have an object reference not set to an instance of an object all the time.

oblique spoke
lunar forum
#

Man. Singletons are confusing as hell.

restive ice
#

They make it very easy to start accidentally writing classes that have multiple responsibilities

#

and you want to stick to the Single Responsibility Principle as much as possible.

#

Anyway, does anyone know why one of my components returns null when added?

#

They both extend from UnifyBehaviour which extends from MonoBehaviour

#

oh I think I figured it out.. it has something to do with my assembly references

#

I had the FooMono behaviour in my edit mode test folder

#

it's kind of weird that it just becomes null instead of throwing me an error...

lunar forum
restive ice
#

wah?

#

can you give a more concrete example?

hollow stone
sacred condor
#

I noticed that after I lock my cursor, I get a large pointer delta afterwards the first time I move in my LateUpdate camera movement.
I tried skipping a frame which worked for normal update but not this time, still getting a large jump

restive ice
#

i've been working on a replacement DI framework

#

aiming for it to be a little less of a learning curve

#

it won't be as extensive though

#

if youre interested i can dm you the repo

modest nova
#

guys I cant access TransformAspect, its giving an error that it cant be found
private readonly TransformAspect _tras;
i have included the using Unity.Transforms;

hollow stone
modest nova
#

no one has commented they are having issues with this so Im assuming it worked for them

#

sorry this doesnt show here

simple egret
#

Do you only get the errors in VS, or are they also there in your Unity Console?

modest nova
#

also in console

#

Assets\Scripts\Component\JellyAspect.cs(11,42): error SGA0007: Aspects cannot contain instance fields of type other than RefRW<IComponentData>, RefRO<IComponentData>, EnabledRefRW<IComponentData>, EnabledRefRO<IComponentData>, DynamicBuffer<T>, or Entity. ()

simple egret
#

Oh yeah that's not your usual C# error

modest nova
#

yeah 🥶

#

the other error is this

#

Assets\Scripts\Component\JellyAspect.cs(11,26): error CS0246: The type or namespace name 'TransformAspect' could not be found (are you missing a using directive or an assembly reference?)

hollow stone
modest nova
#

I dont know what that means

#

if your asking if this is a library built by unity then yes

hollow stone
modest nova
#

I dont get it but okay XD

#

private readonly Unity.Transforms.TransformAspect _tras;

#

like this?

hollow stone
#

If you didn't create it it's not the issue, no worries.

modest nova
#

yeah 😢

leaden ice
modest nova
#

yes

leaden ice
#

which versiopn

chrome horizon
#

Hi everyone! I was wondering if anyone could help me on a raycast thirdperson issue. Basically my raycast shoots to the centre of the world (no idea why)(Video: https://www.dropbox.com/s/qst0c00mgn6wzzr/Unity_mVZHCyrHU1.mp4?dl=0)

cam = GameObject.Find("MainCamera").GetComponent<Camera>();
 Debug.DrawLine(cam.transform.position, cam.transform.forward, Color.green); print("Hit");
        if (Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, pickupDistance, pickupLayer))
Dropbox

Shared with Dropbox

modest nova
leaden ice
#

So it doesn't make sense to use it in DrawLine

#

it's a direction vector

#

If you want to provide a direction vector, use DrawRay

#

DrawLine expects two positions

#

DrawRay expects a position and a direction

chrome horizon
#

I was using that before but it doesn't show where it lands

leaden ice
#

You need to conditionally draw different things when it hits or doesn't hit

chrome horizon
#

How do I do that?

leaden ice
#

when it hits you can do a DrawLine between the ray origin and the raycast hit

#

when it doesn't, do the normal DrawRay

leaden ice
chrome horizon
#

Do you have the code to drawline?

leaden ice
#

wdym

chrome horizon
#

The raycast is in an if

#

How do I display the raycast

leaden ice
#

Using DrawLine and DrawRay as we have been discussing 🤔

chrome horizon
#

When I use DrawRay it's like 2cm long

leaden ice
#

It's as long as you tell it to be

#

perhaps you should use pickupDistance as the length of the ray

modest nova
#

is
private readonly RefRW<LocalToWorld> localToWorld;
the same as
private readonly TransformAspect localToWorld;

modest nova
#

oh okay 😢 thanks

leaden ice
#

one has type RefRW<LocalToWorld> and the other has type TransformAspect

modest nova
#

transformaspect is not being accessed, I think it has been removed or my library is corrupted maybe?

chrome horizon
#
Debug.DrawRay(cam.transform.position, cam.transform.forward, Color.green); print("Hit");
        if (Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, pickupDistance))//, pickupLayer))
        {
hollow stone
leaden ice
chrome horizon
#

I thought that you meant before that you draw the raycast after the if statement

leaden ice
#

Yes

#

you need to draw after the raycast

#

that way we can tell if you hit anything or not

chrome horizon
#

Like this?

if (Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, pickupDistance))//, pickupLayer))
        {
            Debug.DrawRay(cam.transform.position, cam.transform.forward, Color.green); print("Hit");
modest nova
leaden ice
magic fossil
#

I'm seeing GC allocs from calling .Add() on a dictionary. Is that to be expected?

leaden ice
hollow stone
chrome horizon
#

What's the code to draw a line from the position to the landed raycast

leaden ice
#

and use the ray origin and the hit point

modest nova
chrome horizon
waxen jasper
#

Can anyone take a crack at what I need to do to fix these errors? They're stopping me from creating a build.

chrome horizon
#

@leaden ice Ahh that looks so much better. It does seem to be colliding with my player, how can I work around that

leaden ice
leaden ice
chrome horizon
#

How do I make a raycast ignore a tag?

leaden ice
#

you don't

#

that's what the layermask is for

waxen jasper
leaden ice
#

you make it ignore layers

leaden ice
#

shader graph is shader graph

#

visual scripting is different

#

If you're not using Visual Scripting just uninstall the package

waxen jasper
#

Oh. let me double check

chrome horizon
#

@leaden ice You life saving, cheers for the help!

waxen jasper
magic fossil
inner yarrow
#

I've never really had this issue before, and to my knowledge I'm not doing anything unusual, but I am having a lot of my smaller rigidbodies falling straight through the floor. Any ideas how to fix this?

leaden ice
#

Also if/when the Dictionary resizes, it will allocate memory as well

magic fossil
leaden ice
#

structs stored in a dictionary are stored in the dictionary's internal arrays, which are in the heap

leaden ice
glossy basin
leaden ice
#

this will prevent unexpected allocations later on

#

at the expense of doing the allocation immediately

inner yarrow
magic fossil
leaden ice
#

You'll see similar behavior with any of the dynamically sized collection types in C# including List, Queue, Stack, etc...

magic fossil
leaden ice
#

but if resizing happens - that can take additional time when adding things, since you might need to reallocate and copy the data, and this also produces garbage (in the form of the previous, smaller array which is discarded) as you see

#

So - it's a tradeoff

magic fossil
#

OK, makes sense. And the Garbage Allocation only occurs when the dictionary is resized because it discards the previous dictionary (and allocates to clean up the corresponding references on the heap)?

leaden ice
#

well it allocates a new one, and leaves the old one for the Garbage Collector to clean up, yes

#

the allocation is what is caught in the profiler I believe

magic fossil
#

I understand now. Thanks so much for your help! 🙂

sweet marsh
#

got a bit of a problem, I've got 2 layer one called "Ship" and the other called "MapView" I also have 2 cameras in the scene and i want each one to render one of the layers each. culling masks is the solutuion right? issue is when I hide "Ship" from the mapview camera it seems to stop rendering both layers

Culling mask settings:
Ship + MapView = everything rendered (intended)
Ship only = only ship rendered (intended)
MapView only = neither ship nor mapview rendered (unintended: mapview should be rendered)

leaden ice
#

Also this isn't a code issue

sweet marsh
#

ah, my apologies, i'll move there

heady fable
#

Quick question about some code, can I post an image to display it?

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.

heady fable
#

I'm trying to use waypoints on a prefab because the prefab is being spawned but when it spawns it doesnt move?

leaden ice
#

but Move() isn't called unless you're close to the target already

stray stratus
#

my VR game keeps freezing for half a second then unfreezing for 4 seconds then freezes etc... . I hear this is somewhat common and was wondering if there is a fix. It happened right after XR Origin.

inner yarrow
#

Someone who's good at math, how would you calculate a direction that is perpendicular to another direction (or in other words, given the normal of a plane, find any direction that travels along said plain).

unkempt sail
#

Vector3.ProjectOnPlane

#

its generally used to compress a 3D direction to some 2D direction

inner yarrow
unkempt sail
#

I recommend spending 60% of your time reading the documentation

#

Unity generally takes care of most things

unkempt sail
#

try reseting your XR profile

#

going into release mode

inner yarrow
unkempt sail
#

np

night harness
#

Is there a way to limit a UnityEvent to specific functions, and possibly pre-load a specific class?

#

Just to make the inspector more designer friendly

unkempt sail
#

you can make it pre-load instances of components, but not really limit shown functions

#

it basically shows all public functions specific to that class

night harness
#

Yeah makes sense, figured there might of been a niche feature to do it. not a dealbreaker just would have been nice

#

How would I go about pre-loading a specific instance? in this case i just want it to be itself

unkempt sail
#

let me check my claims

stray stratus
unkempt sail
#

depends on your editor version, check with google

stray stratus
#

I dont really know what a profiler is so Imma google that first

mystic spade
#

This is a simple code for running a smooth trail movement:

#
using UnityEngine;

public class SimpleTrail : MonoBehaviour
{
    // Trail
    private TrailRenderer Trail;

    // Speed & Properties
    public float MoveSpeed = 2.85f;

    // Time 
    private float Duration = 0;
    public float OperatingDuration = 4;

    // Booleans
    private bool IsDirectionPositive = true;

    private void Update()
    {
        if (IsDirectionPositive)
        {
            if(Duration < OperatingDuration)
            {
                Duration += Time.deltaTime;
                transform.Translate(transform.TransformDirection(transform.up) * MoveSpeed * Time.deltaTime);
            }
            else
            {
                Duration = 0;
                IsDirectionPositive = false;
            }
        }
        else
        {
            if (Duration < OperatingDuration)
            {
                Duration += Time.deltaTime;
                transform.Translate(transform.TransformDirection(-transform.up) * MoveSpeed * Time.deltaTime);
            }
            else
            {
                Duration = 0;
                IsDirectionPositive = true;
            }
        }
    }
}

mystic spade
unkempt sail
stray stratus
#

it seems like a profiler is where you can check performance, is that correct?

unkempt sail
#

what you can do is write a custom editor I guess, that takes in a specific type in its definition like CustomEvent<Player>, maybe also add a function attribute to public functions that makes it seen to that editors dropdown

slow grove
#

Hey guys, what's the new input system's equivalent to Input.getAxis("Mouse X") and mouse Y respectively? Using the Delta [Mouse] path seems to have a lot less precision than that

slow grove
#

I think that's what I'm using right now:

#

This one just seems a lot more jittery because it uses discrete pixel values rather than some smooth function from -1 to 1..

#

aand I just realized I can probably divide it by the screen width and height to smooth it out

soft shard
# slow grove This one just seems a lot more jittery because it uses discrete pixel values rat...

AFAIK, it just gives you the difference the mouse moved, so it likely would be much larger than -1 and 1, im not sure if dividing that difference by the screen resolution would give you a smoother value, though you can try it, or multiply it by deltaTime, or I think you should be able to add a processor to clamp or normalize the value, but depending on what your trying to do, you could just check if the difference is less than 0 or not

unkempt sail
polar marten
#

i think it is indeed just the delta binding

unkempt sail
#

the new input system is so finicky

wet condor
#

why my wheel collider and lines are not the correct manner ?

slow grove
cobalt wave
wet condor
cobalt wave
wet condor
stable osprey
#

anyone has any tips & tricks for integrating Epic Online Services SDK to a Unity game?

stable osprey
#

wow you're so good

#

must be years in the industry huh

plucky inlet
#

google term "unity epic games sdk" ... not really a fact of experience 😄

stable osprey
#

ok sry i'm tilted because this is still a headache after days of trying 😄

plucky inlet
#

Did you try that page already and have issues? Or did you just not find it?

stable osprey
#

yeah that's where I downloaded the SDK from 😛

plucky inlet
#

Why not just use that sdk with its tutorial dwon the page. They even made a Unity script example on how to use it. So maybe try to add this and come back when you are stuck 🙂

stable osprey
#

cool, thanks

open wasp
#

my scroll rect is overflowing and putting a mask or rect mask 2d breaks the ui really badly. is there another way to hide the scroll rect behind other ui?

stable osprey
#

it'll work properly if you put a background behind it

#

leave the mask on, and just add a black image on a GameObject that's first in the UI canvas's hierarchy

open wasp
#

it's on a panel and the panel i want it to render behind is not rendering on top of it

stable osprey
#

is that resolution correct? 1242x2208

#

anyway

open wasp
#

it is phone resolution

#

dont mind

#

this is a mobile app

stable osprey
#

so the upper part definitely doesn't have a background

#

are yu sure you're not turning the main panel off while scrolling?

#

the issue you've shown would be caused if there is no background and camera doesn't clear. No other cases 😛

open wasp
#

as in just an image behind it?

stable osprey
#

yup

#

seeing you don't have a camera in the scene, it definitely doesn't clear

#

adding a camera in the scene would also fix it, but you'd be left with the default Unity background -- likely something u don't want in UI apps

open wasp
#

i get this issue instead

#

should i just stick a camera back in?

stable osprey
#

seems you're scrolling the container of the rect instead of the scroll rect content

#

I'd say create a default scroll rect and work from there without changing the references -- or check where the proper references go, and copy that to your Scroll Rect

open wasp
stable osprey
#

yeah content shouldn't be the viewport -- Content var should be referencing the 'Content'

open wasp
#

oh wait

#

i didnt realize i did that

stable osprey
#

easy to mess up, lol

#

while you're at it, pump the scroll sensitivity up to 40 or 70. It's much better for in-editor testing

open wasp
#

thx, i got it working perfectly now

#

didnt realize i was just small brained

stable osprey
#

lmao.. no definitely not that.. Unity UI is a pain to get started with.. especially scroll rects and layout groups

fading yew
#

Hey all, I recently openned an old project and I'm getting these annoying errors (Google and ChatGPT have been useless). I've deleted the library folder, made sure all my packages are up to date and I've tried on a different Unity version. Any ideas? 🙂

plucky inlet
fading yew
#

I've already deleted the library folder*

#

I also did a "Re-import all" which I presume does about the same thing

plucky inlet
#

Did you update your editor you are opening that project with?

fading yew
#

yep! On the latest LTS first, then on the beta as a test

plucky inlet
#

Than I guess you are just using packages which are not preview state any more. Didy ou check your packages?

fading yew
plucky inlet
#

Maybe you have to look at your packages json file

fading yew
#

You think the manager window would not show the update and I have to manually update it there?

#

Is there an easy way to know what the latest version for these are?

plucky inlet
fading yew
#

I don't know :/ must have been about a year old :/

plucky inlet
#

Ah okay, I think you can show hidden packages, one sec

fading yew
#

Yeah there use to be an option in the little dot menu, but I can't find it anymore 🤔

plucky inlet
#

Try to click advanced settings and Show dependencies, then reopen packagemanager and see if there is any update for you

fading yew
#

alright I'll try tthat! unity is restarting...

#

I tried resetting to default and although it seems to help, it's also not really doable because it gets rid of all my custom packages I no longer even have in "my assets". So I rolled back on git

#

Also, I don't see "advanced project settings" but here's the "project settings" windows. I don't see anything about "show dependencies"

#

I think you're onto something with editing the manifest manually. But I'm not sure where to find the right version for every package :/

#

(thank you for your help btw 🙏 )

plucky inlet
fading yew
#

I'll send it to you asap, I tried reseting the packages again but this seems to not just reset to default but entirely remove ALL packages ^^' including unity built in ones...

#

so this is what I see right now ...

#

I'll rollback once more and give you the lock file! 1 sec

fading yew
plucky inlet
paper heart
#

I want to graphics.copy from rendertexture to texture2D, they are both RGB565 with mip maps off and same resolutiob, but it throws mismatch error

plucky inlet
paper heart
#

source is Render Texture RGB565 with resolution 32x32 and mip mapping off, dest is Texture2D RGB565 with resolution 32x32 and mip mapping off

plucky inlet
#

You might have to convert your rendertexture to a base texture, because texture2d and rendertexure are both different inheritance from texture itself

steady granite
#

I have this error in console which points to this line where I set DontDestroyOnLoad to elements in a list referenced in the inspector.
When debugging in visual studio, I don't have any error on these lines and it goes through the rest of the code fine.
It doesn't seem to cause any issue, but I still wonder why it shows up?

plucky inlet
steady granite
#

no, gameobjects in the same opened scene as this script

fading yew
vague slate
#

Is there a way to have 1 ParticleSystem to spawn particles in different places?
For example I move it to position X. Spawn particles. Then move it to position Y and spawn particles. So that previous particles stay intact in previous spot.

thin aurora
rustic ember
#

How can I get the lowest value from a List<int> using a lambda expression?

thin aurora
rustic ember
tepid river
steady granite
thin aurora
rustic ember
thin aurora
#

Otherwise use LastIndexOf

#

You can overload IndexOf with arguments if you want a different occurance

#

Such as list.IndexOf(2, list.IndexOf(2) + 1); to get the second 2 in the list.

cosmic ermine
#

wondering does anyone know how the constructor for Color works? is it the same as a simple Vector4 or does it do something special to it? (it would take too long to explain why this matters...)

calm heath
#

is there any way to join splines together

#

2d

distant owl
#

Hello i am trying to use a line renderer it has been working completely fine before i set up a post processing unit and now i can see its still there but it is invisible does anyone know how to fix this?

cloud smelt
#

I have a tilemap that by default has the wrong rotation for gameobjects

severe coral
#

does anyone know why some of my stuff is disappearing while im in scene view?

cosmic ermine
severe coral
cosmic ermine
severe coral
#

tyty

ember ore
#

Is there any lib/plugin that adds some sort of ingame console to a unity app?
That can be opened and viewed to see logs n stuff?

severe coral
calm heath
#

is there a way to draw 2d spline maps instead of having to customize it with a sprite and dragging all the dots around

trim schooner
#

Also, this is a channel for questions about code

tepid river
#

not sure how to change that, noticed similar things

calm heath
#

how can i join these together

tepid river
tepid river
calm heath
#

where is it

tepid river
severe coral
dusk geode
#

when you use the animation rigging package can you mix procedurally generated animations with traditional animations ?

rustic ember
#

Is this valid code? ```cs
public PlayerState state;

public enum PlayerState
{
    Moving,
    Falling,
    Idle
}

// Start is called before the first frame update
void Start()
{
    int playerState = (int)state;
}```
#

If state == PlayerState.Moving I want playerState to be 0

#

If state == PlayerState.Idle, I want playerState to be 2.
And what does state.ToString() do? Will it say Movingor PlayerState.Moving?

orchid bane
#
public class LevelButton : MonoBehaviour {
    private void Start() {
        button.enabled = false;
        text.text = "";
        if (Mathf.Clamp(PlayerPrefs.GetInt("CompletedLevel", 0) + 1, 1, levelsCollection.levels.Length) 
            >= representedLevel)
        {
            text.text = representedLevel.ToString();
            image.sprite = newSprite;
            button.enabled = true;
            button.onClick.AddListener(() => {
                LevelsCollection.currentLevel = representedLevel;
            });
            changeSceneButton.SetSceneToLoad(levelsCollection.levels[representedLevel - 1]);
        }
    }
}

public class ChangeSceneButton : MonoBehaviour {
    [SerializeField] public UnityEngine.Object SceneToLoad;
    [SerializeField, HideInInspector] private string str;

    private void OnValidate() {
        str = SceneToLoad.name;
    }

    public void SetSceneToLoad(UnityEngine.Object SceneToLoad) {
        this.SceneToLoad = SceneToLoad;
        OnValidate();
    }

    public void LoadScene() { //called from click on UI Button
        SceneManager.LoadScene(str);
    }
}```
I have this code which sets which scene to load with my button. It works fine on my PC but always loads the first level on my phone(
Any ideas how to fix it?
steady moat
#

So, maybe you are not doing it ?

orchid bane
#

Ohhhhh wait

steady moat
tepid river
#

with enums, switch is your friend

switch (state) {
  case PlayerState.Moving:
    playerState = PlayerState.Owo
    breaK;
  default:
    throw new UwuException();
}
rustic ember
#

I guess. But then I need to manually convert it to an integer

#

Because I need it to pick an element in a list

tepid river
#

show that code

#

i bet you 2 cookies that you dont

#

🍪 🍪

rustic ember
#
    public Transform[] abilityObjs;

    public void AbilityButtonUpdate(Ability.AbilityType _type)
    {
        abilityObjs[(int)_type].gameObject.SetActive(true);
    }```
rustic ember
tepid river
#

you could use a dictionary instead that maps AbilityType to object.

rustic ember
#

That's just a bigger mess

tepid river
#

because as soon as you reorder your ability enum, f.e. by adding a new state in the zero place, your array breaks

modest nova
#

What component do I have to add to my entities to make them fall using gravity

tepid river
#

your code works, but its not safe to changes

rustic ember
modest nova
#

cant use rigidbody on entities

rustic ember
warm wren
modest nova
#

yeah I guess thats the plan then, I actually needed everything but I think Ill have to use another physics system

jaunty plume
#

Hello, i have a problem:

{

    SpriteRenderer[] spriteRenderer;
    void Start()
    {
        spriteRenderer[0] = GetComponent<SpriteRenderer>();
        spriteRenderer[1] = GetComponentInChildren<SpriteRenderer>();

    }
    void FixedUpdate()
    {
        float screenHeightInWorldUnits = Camera.main.orthographicSize * 2f;
        float scaleFactorY = screenHeightInWorldUnits / spriteRenderer[0].sprite.bounds.size.y; // THIS IS LINE 18
        spriteRenderer[0].transform.localScale = new Vector3(scaleFactorY, scaleFactorY, 1f);

        float screenWidthInWorldUnits = Camera.main.orthographicSize * 2f;
        float scaleFactorX = screenHeightInWorldUnits / spriteRenderer[1].sprite.bounds.size.x;
        spriteRenderer[1].transform.localScale = new Vector3(scaleFactorX, scaleFactorX, 1f);

    }
}

So, if i run this code, it will say:
NullReferenceException: Object reference not set to an instance of an object
ScreenAutoFit.FixedUpdate () (at Assets/ScreenAutoFit.cs:18)
(Line marked on code)

#

I cant understand, i even put the lines from start together with fixedupdate and still doesnt work

leaden ice
jaunty plume
#

yup

jaunty plume
#

it haves

leaden ice
#

Ok well NRE is always the same

#

Read your error

#

Go to the line

prisma birch
#

What would be a good way to have a nav mesh agent calculate a path to walk around other agents? I want to keep my enemies spread out further from one another rather than bunching up. I can increase the avoidance radius, but that just makes the agent that is in motion push the other agents out of the way rather than having the agent walk around the other agents.

leaden ice
#

Figure out what's null

jaunty plume
#

i tested by putting the spriteRenderer to debug log and i got it on that debug line

leaden ice
#

Or the array itself is null

jaunty plume
leaden ice
#

Because you never initialize the array

#

You never initialized your array

#

It's null

#

And you're getting an error in Start too

jaunty plume
#

i've intialized on start

leaden ice
#

No you didn't

jaunty plume
#

huh?

leaden ice
#

Not in that code

jaunty plume
#

huh?

#

wdym

leaden ice
#

You would need spriteRenderer = new SpriteRenderer[2]; for example

#

Right now your array is just null

jaunty plume
#

you meant this one?

leaden ice
#

Yes

#

It's not initialized

#

Anywhere

jaunty plume
#

wait

#

i have to initialize the whole array? not just elements?

leaden ice
#

Also both of those GetComponent lines will return the same object

leaden ice
jaunty plume
#

wait

leaden ice
#

GetComponentInChildren checks the object itself first

jaunty plume
#

what

leaden ice
#

You'd do transform.GetChild(0).GetComponent

jaunty plume
#

oh

leaden ice
#

Or just assign it in the inspector which is better

jaunty plume
#

yea

#

lemme do it

#

good

opal cargo
#

Hey guys, how can I out an empty raycast in case my function did not hit anything so my code won't throw a null reference exception?
I can't even let the out variable empty, so there has to be some value in it and I can't come up with an idea 😕

private bool CastSelf(Vector3 pos, Quaternion rot, Vector3 dir, float dist, out RaycastHit hit)
{
        // Get Player Capsule params
        Vector3 center = rot * _playerCapsule.center + pos;
        float radius = _playerCapsule.radius;
        float height = _playerCapsule.height;

        // Get top and bottom of Player Capsule collider
        Vector3 bottom = center + rot * Vector3.down * (height / 2 - radius);
        Vector3 top = center + rot * Vector3.up * (height / 2 - radius);

        // Check for hits in given direction and distance, return nearest object as RaycastHit if possible
        if(Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, _tempHits, dist, ~0, QueryTriggerInteraction.Ignore) > 0)
        {
            IEnumerable<RaycastHit> hits;
            hits = _tempHits.Where(hit => hit.collider != transform);
            float closestDistNonAlloc = Enumerable.Min(hits.Select(hit => hit.distance)); 
            IEnumerable<RaycastHit> closestHitNonAlloc = hits.Where(hit => hit.distance == closestDistNonAlloc);  
            hit = closestHitNonAlloc.FirstOrDefault(); 
            return true;
        }
        else
        {
            hit = _tempHits.FirstOrDefault();  // << Can't be empty, still gives error like this
            return false;
        }
}
jaunty plume
leaden ice
opal cargo
#

Works, 2 hours wasted - Thanks 😄

jaunty plume
opal cargo
cold parrot
#

We pick implementation strategies on likely number of hours wasted

finite plinth
#

is there a way to duplicate only the mesh renderer parts of an object?

#

as right now im instantiating an object and then destroying each script component afterwards

#

however that is causing errors with both awake methods and scripts that depend on eachother

#

so im wondering if theres a way to skip the destroy part and only spawn the necessary rendering components upon instantiate

hexed pecan
finite plinth
#

i will try that, thank you

opal cargo
#

Again maybe a n00b question, but I've added a Layermask to my Raycast to ignore the Player, which itself and all childrens were assigned to - but I'm still getting hits from it
Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.NameToLayer("Player"), QueryTriggerInteraction.Ignore)
Any idea?

leaden ice
#

LayerMask.GetMask

opal cargo
#

Well, works again, kinda got the Docs wrong

indigo rampart
#

Anybody got any advice for custom tiles. Say I wanted the player to place a tile, for example a factory tile. Which has a coroutine which basically just does something every X seconds.

So I create a custom tile, but there is no method 'OnTilePlace' or something like that which I can override to start a corouitine? Any ideas?

Is the only option to add the method to the tile and call the method when it gets placed?

example code:
tilemap.SetTile(tile)
tile.StartTimer()

steady moat
#
public class MyOwnTileMap : MonoBehaviour {
  [SerializeField] private TileMap tileMap = null;

  public event System.Action<...> OnTilePlaced;

  public void SetTile(...) {
    OnTilePlaced?.Invoke(...);
    tileMap.SetTile(...);
  }
}

Alternatively, you could try to implement your own tile and trigger an event whenever the tile is created. However, beware to not use the Tilemap as a way to store/update your tile. You should try to limit your usage of the tilemap to render function exclusively.

https://docs.unity3d.com/ScriptReference/Tilemaps.TileBase.html

sonic night
#

help i cant jump with boxcast

#

anyone

#

hello

sonic night
#

what do you mean

thin aurora
sonic night
#

yes

leaden ice
lunar forum
#

How do you reference a game object's script? I have a script attached to an otherwise empty game object called "Logic" and the below code is trying to reference that code so I can use its methods. But I'm hit with an "object reference not set to an instance of an object" error.

{

    Logic l;
    Color pickupColor;
    SpriteRenderer driverSprite;

    // Start is called before the first frame update
    void Start()
    {
        l = GameObject.FindGameObjectWithTag("Logic").GetComponent<Logic>();
    }```
#

The object is in the scene, so I know it's not an issue of there not being an instance of it.

#

Also, feel free to point out the other dozen things wrong about that short snippet of code if you'd like. I feel like I'm doing everything wrong.

leaden ice
#

Is there a good reason you aren't just assigning your reference in the inspector?

thin aurora
#

@naive swallow can you use your macro please thanks

naive swallow
thin aurora
naive swallow
lunar forum
thin aurora
#

@lunar forum ☝️

valid adder
#

I'm writing a grid system but I have a mathematic problem with getting the node from a world position. I basically wanna snap to the node as soon as the target is inside the square around the node (the unity grid is representing the square i mean). However as you can see in the video this is not working right now.

public Node NodeFromWorldPoint(Vector3 worldPosition) {
        float percentX = (worldPosition.x + (width / 2f)) / width;
        float percentY = (worldPosition.z + (height / 2f)) / height;
        percentX = Mathf.Clamp01(percentX);
        percentY = Mathf.Clamp01(percentY);

        int x = Mathf.RoundToInt((width - 1) * percentX);
        int y = Mathf.RoundToInt((height - 1) * percentY);

        return nodes[x, y];
}
public void CreateGrid()
    {
        nodes = new Node[width, height];
        
        var name = 0;
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {

                Vector3 startPosition = new Vector3((width) / 2, 0, (height) / 2) - new Vector3(0.5f, 0, 0.5f);
                Vector3 worldPosition = (transform.position - startPosition) + new Vector3(x, 0, y);

                nodes[x, y] = new Node(true, worldPosition, x, y);
                if (visualizeNodes) {
                    nodes[x, y].createInstance(nodeInstance);
                }
                name++;
            }
        }
    }

How would I tackle this issue? What mathematical mistake have I made?

wanton stratus
#

Can anyone suggest me how many programming patterns i should know for developing hyper casual games fast

stable rivet
static matrix
#

My playerobject is destroyed when it sits on the floor, it has a bouncy rigidbody, which might be the cause. How do I fix this?

indigo rampart
hallow grove
#

hey everyone, I want to create a save system and for that i'd need each object to have a unique, permanent ID. However I can't find anything that allows this (GetInstanceID is not permanent so it won't work) does anyone has an idea on how to create a permanent ID system or is there already something like that in Unity ?

winged mortar
#

They won't be the same on every system though

#

You could use an editor script to automatically assign a guid to every gameobject, that way it would be the same for everyone

hallow grove
#

ok thanks a lot !

hallow grove
winged mortar
thin aurora
# hallow grove hey everyone, I want to create a save system and for that i'd need each object t...

Do you need a unique id because you need to ensure that the saved data is returned to where it was saved from, or just saving in general?
If saving in general, either an unique guid using Guid.NewGuid() or you can use a regular int. For the latter you should check what the last int was that was saved, which is more work.
If you need to keep track of the class that saved it, why not get the full name of the class? typeof(yourClass).FullName

hallow grove
#

thats why i want each object to have a unique and permanent ID

heady fable
#

Quick question trying to get the transform of waypoints and convert it to a vector3 for the NavMeshAgent. I did Debug.Log and it shows its getting the waypoints but its not moving?

reef crater
#

does anybody know how to fix this?

jolly plank
#

If anyone could take a look at my forum post and help me out that'd be fantastic also

elfin tree
#

Can anyone link me to script to save runtime instantiated meshes/prefabs into assets?

rain minnow
swift falcon
#

Anyone know what could be causing this jittering? I only have a Character controller script in the scene.

pliant lake
#

an idea ? I searched on the internet but no topic about this prblm on unity and the available topics was about js and webAPI permissions in short nothing to do I really don't know where it can come from, I tried on the beta 2023 of the software and there on 2022.2.12 both times with HDRP and same problem for both versions :/ thanks for any help!

swift falcon
clear umbra
#

are you lerping the camera?

swift falcon
#

only for the headbob

clear umbra
#

try disbaling the headbob is it still jittering?

#

I'm not sure how you implemented the headbob, but I have a suspicion it is causing the jitter

#

Otherwise, remove one part of your movement script at a time and test that the functionality is indeed working without jitter

#

(Test only Horizonal rotation, then only Vertical rotation, then Only Headbob, then start combining variations of these systems together until you find the culprit)

thick isle
#

I have a list that I am trying to populate from the Inspector, however I think I'm missing something

[Serializable]
public class CharacterStat{ //does base functions
}
[Serializable]
public class HealthStat : CharacterStat
{
//Does health specific things
}
[Serializable]
public class MovementSpeedStat : CharacterStat
{
//Does movement speed things
}

This is my parent child set up for stats to inherit functions but also manage their own specific stuff. I'm struggling to be able to add these individual classes to a list

    [SerializeReference] public List<CharacterStat> statList;

What am I missing here?

hexed pecan
#

That's what I've been doing, though my List's <T> has been an abstract class or interface

thick isle
#

oh let me try I thought about doing that but never ended up testing

hexed pecan
#

Its also initialized in the doc examples so that might be it

thick isle
#

hmm still no dice, I'd imagine its someweird inspector thing because they are just classes and not monobehaviors? i dont know :c

hexed pecan
#

The doc also says that SerializeReference should not be used for UnityEngine.Objects (which MB are) so thats not the issue

#

What if you make a new list variable just to test? And give it an initial value

#

Are you sure that CharacterStat does not inherit from any UnityEngine.Object class?

thick isle
#

nope, the class declaration is just public class characterStat

#

no inheritance

somber nacelle
#

are you sure you want to use SerializeReference there?

hearty perch
#

how to fix this

plush sparrow
#

Is there any way to story json data in application memory instead of file memory?
For Android build

plush sparrow
#

They should be same

vestal geode
leaden ice
hearty perch
#

what is script class

#

isnt it script thats inside a game object

vestal geode
tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

hearty perch
#

its not letting me add script

inner yarrow
#

I'm getting confused with what should be a pretty simple raycast. if(Physics.Raycast(ray, out hit, rayLength, LayerMask.GetMask("Lightsaber"))), it correctly only hits objects that are on the "Lightsaber" layer, but the object returned by hit.transform is the object's parent.

hearty perch
#

it matches

vestal geode
hearty perch
#

im not using that
when i cant understand something i just ask them questions

#

but this time bot cant help

vestal geode
#

The problem with your script was already explained to you in code-beginner, so the next step is to look at beginner scripting tutorials to see how it works in practice
Or google the error for forum threads with more instructions

somber nacelle
# hearty perch

do you perhaps have errors in your console such as errors suggesting you are missing a using directive?

somber nacelle
somber nacelle
#

your class name doesn't match the file name

rain minnow
rain minnow
#

An answer was provided for you there . . .

hearty perch
#

ok i wont

hearty perch
#

big thanks

#

well um then how to change file name

somber nacelle
hexed pecan
#

hit.collider will reliably give you the actual object you hit

inner yarrow
hearty perch
#

OOOOH THAT WAS WHAT class name

#

dang

somber nacelle
inner yarrow
lunar forum
teal silo
#

Hey all, I want to create an enemy that has a sphere (or circle, since it's 2D) of influence that increases a certain stat of the players when inside it. Right now I have it set up with an empty child on the enemy, a sphere collider on said child and a OnTriggerStay2D that executes the code. Then, I made sure that the physics from the player's hitbox wouldn't affect the trigger because the player could hit the enemy through the trigger lol.

It works as intended, but I just get the feeling that changing the physics collisions seems kinda messy and not very good praxis, so I was wondering if any of you would have done it/would do it differently.

#

And while I'm at it, Id also like to ask what you guys would think is the best way to check if the enemy is facing away from the player or not (I would like to implement a backstab feature)

hearty perch
#

hey um

using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;


public class trow : MonoBehaviour
{
    public SpriteRenderer sword;
    public Rigidbody2D rb;
    private float dirX = 0f;
    [SerializeField] private float moveSpeed = 7f;
    public Rigidbody2D rb2;
    public Transform transform;
    void Update()
    {
        dirX = Input.GetAxisRaw("Horizontal");
        if (Input.GetKeyDown(KeyCode.T) && sword.enabled == true);
        {
            rb.velocity = new Vector2(dirX + moveSpeed, rb2.velocity.y);
            if (transform.localScale == new Vector3(-1, 1, 1))
            {
                rb.velocity = new Vector2(dirX - moveSpeed, rb2.velocity.y);
            }
;
            
        }
    }
}```
#

here

#

when i press t and sword is on

#

i want to shoot it

#

shooting is working

#

something simmilar

#

but

#

when i spawn in game

somber nacelle
#

; ending your if statement early

#

make sure your !IDE is configured so it shows warnings about things like that

tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

hearty perch
#

it does it immediately

hearty perch
#

i do have that

hearty perch
somber nacelle
#

then you should have seen the warning about a possibly empty if statement

hearty perch
#

mb

#

but still

#

it immediately shoots sword

somber nacelle
#

well if you've removed that ; then it shouldn't unless there's some other context you aren't providing

hearty perch
#

ok

#

imma fix that later

#

but now uh

#

look at this

#

there is missing ;

#

at if sentance

#

when i fix it

#

it doesnt work the way i want

#

when i dont

#

it works way i want

#

like

#

it works so what sword shoots at way im looking

#

if i dont fix it

#

if i do it just goes to 1 direction

#

to the right

somber nacelle
#

you still have the extra ; on your if statement. it's literally right next to your cursor. remove it

hearty perch
somber nacelle
#

yes

hearty perch
#

okay

#

its all broken now

#

it doent move if i wont move

#

and skips sliding part

#

just teleports to where it would have been if i moved

hard sparrow
#

So I'm trying to refactor in order to have my unit data in a scriptableobject separate from the unit controller - the unit data contains the unique variables and logic for different units (different class for each one), and is executed by the controller (which is generic). Is that dumb?

hearty perch
#

oooH

#

this is the diffrance

#

thats pointless ngl

winged mortar
#

Okay so you don't need to add the {} to use the if statement

#

That's why the ; is valid syntax

#

Watch

hearty perch
#

so i do not need {} ?

#

uh

somber nacelle
#

in your case you do

hearty perch
#

good

winged mortar
#
if (X > y)
      doSomething();

Is the same as

if(X>y)
{
    doSomething();
}
somber nacelle
#

you can exclude the braces only when there is a single statement in the scope of the if statement

hard sparrow
hearty perch
#

i didnt knew that

winged mortar
#

However the first approach only works with a single statement

hearty perch
#

thanks for telling me

winged mortar
#

And is prone to errors

somber nacelle
winged mortar
#

So you should always use {}

#

and just having a ; is a empty line

#

So nothing will be done on that line

#

thus having an if followed by a ; is just and if this then do nothing

hearty perch
#

thanks a lot! i understand now

winged mortar
#
if (X > y);

Is the same as

if(X>y)
{
    ;
}
hard sparrow
#

Are you just not supposed to put logic inside scriptableobjects?

somber nacelle
#

you can. but a lot of people will recommend against it and recommend using scriptable objects only for immutable data

hard sparrow
#

So if you have units with potentially unique variables and methods, you might as well just not bother with SO?

#

As in, an SO won't be sufficient to describe the unit

somber nacelle
#

you can, that's perfectly fine. but if you need to access those unique variables and methods but you've stored the reference to the SO as its base class you'd need to downcast to the correct type to access them

winged mortar
#

You can also convert a scriptablw object to a runtime object, so if a entity can shoot add an enum that it can shoot or melee and then at runtime check which ome is set when instantiating it

hard sparrow
#

In this case I would need to have a separate set of variables on the instance controller since those can be changed by in game effects (while you wouldn't want to change the base data). So then you'd be using the instance for both logic and variables so... does the SO serve any purpose at that point?

winged mortar
hard sparrow
#

Well every time I try to use SOs they end up just not making sense to me

#

I guess it's just for simple data and that's it

#

Also that static switch case example seems just bad

#

I'll just give up on SO for now

winged mortar
#

Can build a system using reflection to get behaviours bound to enums

#

Don't need a switch case

mystic ferry
#

I'm trying to implement a timer that kicks off some methods. I can't use a traditional deltaTime timer (afaik) because this timer is happening inside of an event listener. My solution was to use a simple coroutine with a waitforseconds, but that doesn't seem to be working how I thought it would

void OnStartNewRound()
{
   //some other things
   StartCoroutine(KickoffTimer(timeToWait));
   //the rest of the setup
}
 IEnumerator KickoffTimer(float timeToWait)
   {
      yield return new WaitForSeconds(timeToWait);
   }
#

any input as to what I'm doing wrong here?

somber nacelle
#

a coroutine will not delay the method it is called from, it can only delay itself (or technically it could delay another coroutine if the startcoroutine call is yielded in that outer coroutine)

mystic ferry
#

I see, that was what I was afraid of

#

what can I do to get the effect that I need?

somber nacelle
#

put everything you need to do inside the coroutine and have OnStartNewRound call the coroutine, or subscribe to whatever event with a lambda that just starts the coroutine

mystic ferry
#

gotcha. Thanks

opal cargo
#

Hi guys, got a bit weird behaviour with sorting an array that sometimes only has one item.

int hitLength = Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Ignore);
if(hitLength > 0)
{
    for(int i=0; i < hitLength; i++)
    {
        Debug.Log("Hitlength:"+hitLength + " Hit"+i+": " + hitArray[i].normal + " name: " + hitArray[i].collider.name);
    }
    // Sort array by distance 
    Array.Sort(hitArray,(x,y) => x.distance.CompareTo(y.distance));  
    hit = hitArray.First(); 
    Debug.Log("Hit return: " + hit.normal);  
    return true;
}

By sorting like this I'm getting a normal of (0,0,0) all the time, despite for-loop showing the real normal and a hitLength of just 1.

#

Commenting sort out returns the same normal

leaden ice
#

Anyway you can't really do Array.Sort here

#

because the array is going to be longer than the actual number of hit results

#

You're better off using the List version of CapsuleCastNonAlloc here

opal cargo
#

Found I can do this 🙂

int hitLength = Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Ignore);
if(hitLength > 0)
{
    for(int i=0; i < hitLength; i++)
    {
        Debug.Log("Hitlength:"+hitLength + " Hit"+i+": " + hitArray[i].normal + " name: " + hitArray[i].collider.name);
    }
    // Create comparer to allow comparison of RaycastHit Type
    Comparer<RaycastHit> comparer = Comparer<RaycastHit>.Create((x,y) => x.distance.CompareTo(y.distance));
    Array.Sort(hitArray,0, hitLength, comparer);
    // float closestDistNonAlloc = Enumerable.Min(hits.Select(hit => hit.distance)); 
    hit = hitArray.First(); 
    int index = 0;
    foreach(RaycastHit rchit in hitArray)
    {
        Debug.Log("Hitlength:"+hitLength + " Hit"+index+": " + rchit.normal );
        index++;
    } 
    return true;
}
leaden ice
#

and making sure the list is cleared first

#

that works too

opal cargo
#

And reset Array before

leaden ice
#

I didn't realize Sort has that overload

#

that's perfect for your use case

#

still

#

hitArray[0] will be faster than hitArray.First();

opal cargo
#

Sure, will change that 🙂

#

Took me a bit of crawling through Array.cs to find this but it's easy to use and I guess way faster than dealing with lists

winged mortar
#

Could do a lil bit of optimization by not creating a comparer every time the function is called

cloud haven
#

hello

blazing void
#

hi, I've locked my mouse in position with Cursor.lockState = CursorLockMode.Locked;, and then I gather user input through

float mouseX = Input.GetAxisRaw("Mouse X") * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensY;

but, on my reset function I need the mouse to return back so both Input.GetAxisRaw("Mouse X") and Input.GetAxisRaw("Mouse Y") return 0. Is this possible?

dusk apex
#

The mouse should still be at center and not moving.

#

Maybe just set mouseX and mouseY to zero if you're wanting to default the values to zero in some function.

blazing void
#

sorry I’m new to unity and C#, what is a delta? and I use the input.getrawaxis in my update function. I’m making a new function that can reset the position of the player, I can easily move them but when I try to rotate them the function I have for turning just immediately puts them back to their previous position due to the Input.GetAxisRaw not resetting as well and so the game keeps them looking in that direction. I hope that makes sense, please correct me if I’m wrong

rain minnow
buoyant crane
blazing void
#

ah okay that makes sense, thank you all

buoyant crane
blazing void
#

I will do my best to explain but if it’s unclear then don’t worry about trying to make sense of it

#

so my cursor is locked and the player can move the mouse left and right to turn left and right, and as it is just a first person character I just rotate the camera that is inside the players rigid body, and all works fine. When I try to teleport the player to a location it also works perfectly fine, but when I try to teleport them and rotate them so they’re facing a specific direction, then problems arise. I tried many methods to rotate the player, such as transform.eulerAngles, Quaternions, all that sort of stuff, and the player would rotate but then instantly be rotated back to their original direction. I presume this was because the program still thinks the mouse is in a place which links to a specific direction to face in, but I’m not sure. I’ve tried changing stuff but it hasn’t really worked, and so I came here for help

buoyant crane
#

like the rotation code

blazing void
#

that’s to look up and down

buoyant crane
blazing void
#

sure give me a few minute

#

should I use paste bin or just send it here

buoyant crane
blazing void
#

^ that is my code for the generic turning of the camera

buoyant crane
blazing void
#

wow, it was that simple

#

i kid you not i spent like 3 hours trying to figure out a solution 😂

buoyant crane
#

rotation can be tricky

blazing void
#

well, thank you very much for that!

buoyant crane
#

no problem

night harness
#

I can think of some janky ways to forward the calls but is there a decent way to get ontrigger function calls on behalf of another object?

buoyant crane