#archived-code-general

1 messages · Page 161 of 1

steady moat
#

You know that they will happens don't you ?

#

You just calculated everything that would happens

pure cliff
#

Let's say attack anim is 6 frames, movement is just a translation so can be any speed but it's 1 unity unit.

Let's say attack-move-attack. So if I had a min of lets say 15 frames, that's 6 frames to attack, 3 frames to move, 6 frames attack again

#

Effectively I can have a list of (float minTime, float maxTime) for each entity

#

And then I have to pick the "right" time that satisfies all of those?

steady moat
pure cliff
steady moat
#

There is just one outcome possible when all action has been chose doesnt it ?

pure cliff
#

I can speed up or slow down any entities animations and movements

#

So some enemies may have an ability that takes 1s, some may just be idling which will have a min of 0 and max of infinite

steady moat
#

You know how much time it would take given a normal execution. Then you just normalize it.

#

I do not understand why you have a min and max. It seem clear to me that if you are doing a turn by turn, when all action are chosen, there is only 1 outcome.

pure cliff
#

I guess there is no max, I can infinitely slow down anything, so its just mins right?

steady moat
#

I'm not talking about slowing down or not.

#

I'm talking before even doing any of that.

#

You know that it is going to take Xs for entity A and Ys for entity B.

#

The you just normalize

pure cliff
glacial loom
#

hello I don't really understand, which class does this go in?

steady moat
steady moat
pure cliff
#

But in synch cuz multiple turns can be "queued"

steady moat
#

Then how could you make it works ? If anyone can just play whatever they want at anytime.

pure cliff
#

Player can click 3 squares over, which is 3 turns worth of movement, so every other entity will do 3 turns of actions

steady moat
#

So, it is turn by turn. Everyone choose an action, then it is executed at the same time.

pure cliff
#

But I pre-calc all the 3 turns of moves first, then hand everyone their queues of actions.

But to avoid weird looking playout, I want them to know how long each turn will take so everyone stays in sync

steady moat
#

Then, you still know how much time it is going to take.

#

You can just normalize the time.

#

For every entities

pure cliff
#

Exactly

steady moat
#

Then what is the issue ?

pure cliff
#

The tricky part is just that the player can do more than 1 move in 1 round due to auto attacks

steady moat
#

This also is known

pure cliff
#

Doing the sort of shrink/grow math to make it fit

carmine wind
#
Vector3[] faceDirections = {
transform.up, -transform.up,
transform.right, -transform.right,
transform.forward, -transform.forward
};
....
private bool CheckFaceCollision(Vector3 faceDirection)
{
    Ray ray = new Ray(transform.position, faceDirection);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, 1, LayerMask.GetMask("Floor")))
    {
        if (Mathf.Approximately(Vector3.Dot(ray.direction, Vector3.up), 0))
            return true;
        return false;
    }

    return false;
}

I have this script to check if my cubic box is laying flat on the floor but it doesn't seem to be working I'm not sure what I'm doing wrong.
it's supposed to do a raycast to see if it hits the floor and also at what angle. if it's perpendicular it's sitting flat

steady moat
#

Why wouldnt it be ?

pure cliff
steady moat
pure cliff
#

I think it's all just min times and I just pick the slowest min time, theoretically

steady moat
#

You divided all by the larger

pure cliff
#

But then maybe I still need a static const min time any given round can be?

steady moat
#

There is no need for a min.

#

Nor a max

#

Just the longest

pure cliff
#

Well I want to specify that certain actions cannot go any faster than x

#

Like "this can't take any less than 0.6s" to avoid the anim looking bad

sinful ginkgo
#

I have tried everything i could think of including the answers in the forums to fix it but it still shows the same error

steady moat
#

In fact, you could even use this as the normal time.

pure cliff
#

It seems like I just assign a min to everything, plus one static "round" min that makes it so rounds can't go any faster than say, 0.5s, and I just get the max of them all to get the fastest I can possibly go without exceeding any limit

#

I can then nicely default it to 0 on my MBs and only need to set it for animations that actually need a min

#

That... might work

steady moat
#

If you find the largest, then normalize base on it. Everything will be longer. I would start by that, this is simple.

#

If it really looks goofy, you could then figure out how to properly make the action longer to fit the longest one.

sinful ginkgo
heady iris
#

and have you done anything to verify that it's actually raycasting in the way you expect?

#

i.e. using Debug.DrawRay

leaden ice
#

if you're not using the hit normal I don't see the point of the raycast

carmine wind
#

ok I'll try both of your suggestions

leaden ice
#

also I'm unsure why you even need to a do a raycast in the first place

#

shouldn't you just compare transform.up to Vector3.up?

lean sail
#

it still can be rotated by laying flat, so you just compare the transform.up to like vector3.up, -vector3.up etc

#

or all the transform.up etc to vector.up

heady iris
#

if the ground is flat, then a raycast perpendicular to the ground's normal vector will never hit it

carmine wind
heady iris
#

also, Mathf.Approximately is still a very tight tolerance

#

i wish there was a convenient Mathf.Distance method

#

Mathf.Abs(x-y) < 0.01f works, I guess

leaden ice
#

I don't see what the raycast is for

carmine wind
#

it could be in the air

#

actually no I'm using it in OnCollisionStay nvm

elfin tree
#

Hey, I have this code (image 1) that takes a terrain that's already in the scene and generate copies around it, it works, only thing is, it seems like the instantiated ones are not quite like the initial one in their position, probably due to the way I instantiate them and a gap is created ONLY BELOW THE STARTING ONE, any idea how I can resolve this?

lean sail
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.

elfin tree
hidden compass
#

ur using intialTerrainPos.x for both the X and Z coord

#

not sure if that might be causing the gap

elfin tree
hidden compass
#

np

slim flower
#

I have a quick question, Im making a scriptable object that acts as the info for a team, it has inside of it a int for a index, int for score, and a list of a component which all the players have which acts as a list ofa ll palyers on that team. When i try to edit or add values to this list, for example. (Teams is a list of all of the scriptable objects):

Teams[index].Players.Add(player);

this returns an error saying something is null. How can i fix this. The code for the list "Players" in the scriptable object code is

public List<TeamTag> Players;

i dont understand why this isnt working. Any help is appreciated :)

leaden ice
#

you have to figure out which

#

you can attach the debugger or use Debug.Log

slim flower
#

I have

leaden ice
#

and?

slim flower
#

none of them seem to be

leaden ice
#

one of them must be

#

Show your investigation steps

slim flower
#

let me check again

leaden ice
#

and what the results were

slim flower
#

alr

#

oh wait

#

i think i may be stupid

#

dont i have to initialize the list by using the code

= new List<TYPE>()

#

._.

leaden ice
#

yes that will be necessary if the list isn't being serialized by Unity

slim flower
#

thank you

#

let me try to do that

#

ahhaha i cant believe i forot about that part

#

everything seems to work now

#

thank you so much, i cant believe i was so stupid

tawdry jasper
#

I installed the official newtonsoft json package, but in vscode it flags using Newtonsoft.Json; as an error?

somber nacelle
#

Regenerate project files

#

Also if you're using assembly definitions don't forget to reference the assembly

static matrix
#

im doing a random movement thing, and my animals keep moving up and to the right
is this a psudorand problem? or is it something in my code (Ill send it if its more likely to be the latter)

somber nacelle
#

Show code

static matrix
#
Tile TryGetValidTile()
    {
        start:
        List<Tile> AdjTiles = TileOn.GetAdjacentTiles();
        Tile TryTargTile = AdjTiles[Random.Range(0, AdjTiles.Count)];
        if (TryTargTile)
        {
            if (TryTargTile.IsWater)
            {
                goto start;
            }
            else
            {
                return TryTargTile;
            }
        }
        return TileOn;
       
    }
//_________________________TILE SCRIPT_________________
public List<Tile> GetAdjacentTiles()
    {
        List<Tile> adjacentTiles = new List<Tile>();
        adjacentTiles.Add(GetComponent<Tile>());
        var TilesUp = GetAdjacency(transform.position + new Vector3(0, 0.85f));
        adjacentTiles.Add(TilesUp);
        var TilesDown = GetAdjacency(transform.position + new Vector3(0, -0.85f));
        adjacentTiles.Add(TilesDown);
        var TilesNE = GetAdjacency(transform.position + new Vector3(Offset.x, Offset.y));
        adjacentTiles.Add(TilesNE);
        var TilesSE = GetAdjacency(transform.position + new Vector3(Offset.x, -Offset.y));
        adjacentTiles.Add(TilesSE);
        var TilesSW = GetAdjacency(transform.position + new Vector3(-Offset.x, -Offset.y));
        adjacentTiles.Add(TilesSW);
        var TilesNW = GetAdjacency(transform.position + new Vector3(0, Offset.y));
        adjacentTiles.Add(TilesNW);
        return adjacentTiles;
    }
//MORE TILE SCRIPT
 Tile GetAdjacency(Vector3 direction)
    {
        var Check = Physics2D.LinecastAll(transform.position, direction, Tiles);
        if (Check.Length > 1)
        {
            return Check[1].collider.GetComponent<Tile>();
        }
        else
        {
            return thisTile;
        }
    }
#

first one is animal script

#

this is not my finest code

#

idk, I dont mess with mobile or MP

molten thicket
#

Fixed my problem - I'm an idiot.

2 days of troubleshooting and I forgot to add the code under the correct switch case 🥲

languid hound
#

Is there a way to stylize GUILayout?

#

For example changing the text with rich text or maybe if its possible even getting a reference to the GameObject (If its even on one)

#

Right now doing <u>text</u> does nothing

dusk apex
static matrix
#

? in which part

dusk apex
#

Every call to GetAdjacency(...) above.

#

Direction would be target position minus initial position.

static matrix
#

oh, that gets the adjacent tile in the provided direction

dusk apex
#

Not initial position plus offset. This would only yield another position.

static matrix
#

its a linecast, not a raycast
I named it poorly, it should be endpos

dusk apex
#

Alright, makes more sense now.

#

Assuming this isn't being spammed recursively, you could print the members of the collection or inform us what's happening and isn't.

lean sail
#

is there a way to make a prefab reference itself, without it swapping the reference to be the instantiated object?
I know theres the whole asset database solution but just wondering if theres a different method. This is for some network object pooling thing where I want the object to return itself to the pool, and the pool needs the prefab reference

static matrix
#

example of all the things going right

#

(Yellow dots)

#

click, select none

#

scroll up

#

do you see "none" now?

thick terrace
lean sail
thick terrace
#

it would be nicer to have unity do it for you but i think it'll always "fix" direct serialized refs

lean sail
#

yea understandable, itd probably be way more of a pain if it didnt assign the reference tbh

stark nimbus
#

is there a way to simplify this?

        string CooldownToString(double cooldown)
        {
            string left = string.Empty;
            TimeSpan passed = TimeSpan.FromSeconds(cooldown);
            if ((int)passed.TotalDays > 0) left += passed.Days + (passed.Days == 1 ? " day" : " days") + (passed.Hours == 0 && passed.Minutes == 0 ? " and " : (passed.Hours > 0 || passed.Minutes > 0 ? ", " : " "));
            if (passed.Hours > 0) left += passed.Hours + (passed.Hours == 1 ? " hour" : " hours") + (passed.Minutes == 0 ? " and " : (passed.Minutes > 0 ? ", " : " "));
            if (passed.Minutes > 0) left += passed.Minutes + (passed.Minutes == 1 ? " minute" : " minutes") + " and ";
            left += passed.Seconds + (passed.Seconds == 1 ? " second" : " seconds");
            return left;
        }
#

it works, but I couldn't think of a way to specifically not show 0 seconds without throwing off the logic that separates every component with either a , or an and

spark shore
#

any thoughts on why this 9 sprite is rendering so weird on the canvsas? Is it cut correctly? Thank you!

spark shore
#

ok thank you

stark nimbus
#
(double)90061.0f)
somber nacelle
#

why do you keep writing float literals and casting them to double? 🤔
just use a double literal. also float should be able to be implicitly cast to double

stark nimbus
somber nacelle
steady moat
#

@stark nimbus did you take time to read the article I sent ?

stark nimbus
#

yes, I know how .ToString() format methods work, for both TimeSpan and DateTime

steady moat
#

And, you know that you can format them ?

stark nimbus
leaden ice
steady moat
stark nimbus
spring creek
stark nimbus
#

my code adds a , between days/hours/minutes if there are more than 3 element to show, and will show and before seconds if there are more than 2 elements to show

leaden ice
#

The whole thing would be something like left = "{0:%d} day, {0:%hh} hour, {0:%m} minute, and {0:%s} seconds";

stark nimbus
surreal nymph
#

hi can any of you help me with sum

stark nimbus
surreal nymph
#

its unity related not much code related if thats ok

leaden ice
surreal nymph
#

i put it in general

#

ok

quartz folio
surreal nymph
#

ok sorry

stark nimbus
steady moat
stark nimbus
#

the only problem I see with my code is

#

I can't get rid of x seconds at the end without throwing off the logic that separates each element with either a , or an and

#

so it will always show seconds, even if it is 0 seconds

#

unlike days, or hours, or minutes, which won't show if they're 0

steady moat
#

That is because you concat the "and" or "," after instead of before

#

Also, it is kinda hard to read. I suggest you use variable and more spacing.

stark nimbus
# steady moat Also, it is kinda hard to read. I suggest you use variable and more spacing.
string CooldownToString(double cooldown)
{
    string left = string.Empty;
    TimeSpan passed = TimeSpan.FromSeconds(cooldown);

    if ((int)passed.TotalDays > 0)
    {
        left +=
            passed.Days +
            (
                passed.Days == 1 ?
                " day" :
                " days"
            ) +
            (
                passed.Hours == 0 && passed.Minutes == 0 ?
                " and " :
                (
                    passed.Hours > 0 || passed.Minutes > 0 ?
                    ", " :
                    " "
                )
            );
    }

    if (passed.Hours > 0)
    {
        left +=
            passed.Hours +
            (
                passed.Hours == 1 ?
                " hour" :
                " hours"
            ) +
            (
                passed.Minutes == 0 ?
                " and " :
                (
                    passed.Minutes > 0 ?
                    ", " :
                    " "
                )
            );
    }

    if (passed.Minutes > 0)
    {
        left +=
            passed.Minutes + (
                passed.Minutes == 1 ?
                " minute" :
                " minutes"
            ) +
            " and ";
    }

    left +=
        passed.Seconds + (
            passed.Seconds == 1 ?
            " second" :
            " seconds"
        );


    return left;
}
#

lol

dusk apex
#

How to post !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.

dusk apex
#

📃 Large Code Blocks
Large code blocks should be posted as links to services

stark nimbus
steady moat
# stark nimbus I was very sleepy when I coded this, didn't even think of it
private static string Pluralization(int value, string singular, string plurial)
    {
        return value == 1 ? singular : plurial;
    }

    private static string ConcatEnumaration(List<string> values)
    {
        string value = "";
        for(int i = 0; i < values.Count; ++i)
        {
            value += values[i];
            if(i < values.Count - 1)
            {
                string joint = i == values.Count - 2 ? " and " : ", ";
                value += joint;
            }
        }
        return value;
    }
    
    static string CooldownToString(double cooldown)
    {
        string left = string.Empty;
        TimeSpan passed = TimeSpan.FromSeconds(cooldown);
        
        List<string> values = new List<string>();
        if ((int)passed.TotalDays > 0)
        {
            string days = $"{passed.Days} {Pluralization(passed.Days, "day", "days")}";
            values.Add(days);
        }
        if (passed.Hours > 0) 
        {
            string hours = $"{passed.Hours} {Pluralization(passed.Hours, "hour", "hours")}";
            values.Add(hours);
        }
        if (passed.Minutes > 0) 
        {
            string minutes = $"{passed.Minutes} {Pluralization(passed.Minutes, "minute", "minutes")}";
            values.Add(minutes);
        }
        if (passed.Seconds > 0)
        {
            string seconds = $"{passed.Hours} {Pluralization(passed.Seconds, "second", "seconds")}"; 
            values.Add(seconds);
        }

        return ConcatEnumaration(values);
    }
#

It can be simplify even more.

#

But at least, it is more readable

stark nimbus
#
string CooldownToString(double cooldown)
{
    string left = string.Empty;
    TimeSpan passed = TimeSpan.FromSeconds(cooldown);

    if ((int)passed.TotalDays > 0)
    {
        left +=
            passed.Days +
            (
                passed.Days == 1 ?
                " day" :
                " days"
            );
    }

    if (passed.Hours > 0)
    {
        left +=
            (
                passed.Days == 0 ?
                string.Empty :
                (
                    passed.Minutes > 0 || passed.Seconds > 0 ?
                    ", " :
                    " and "
                )
            ) +
            passed.Hours +
            (
                passed.Hours == 1 ?
                " hour" :
                " hours"
            );
    }

    if (passed.Minutes > 0)
    {
        left +=
            (
                passed.Days == 0 && passed.Hours == 0 ?
                string.Empty :
                (
                    passed.Seconds > 0 ?
                    ", " :
                    " and "
                )
            ) +
            passed.Minutes +
            (
                passed.Minutes == 1 ?
                " minute" :
                " minutes"
            );
    }

    if (passed.Seconds > 0)
    {
        left +=
            (
                passed.Days == 0 && passed.Hours == 0 && passed.Minutes == 0 ?
                string.Empty :
                " and "
            ) +
            passed.Seconds +
            (
                passed.Seconds == 1 ?
                " second" :
                " seconds"
            );
    }

    return left;
}
#

works perfectly

stark nimbus
heavy wren
#

I have a script that generates a cube of varying levels of detail from Unity's primitive plane mesh. It will work perfectly fine until the "countPerFace" exceeds 50, then the generated mesh starts to breakdown and I don't know why. Here is the MonoBehaviour, just plug in primitive plane mesh https://hatebin.com/lcywojqrzb

quartz folio
#

(it may not work, it's just a hopeful guess)

brittle sparrow
#

I'm trying to figure out how ContactPoint2D's are formed upon OnCollisionEnter2D, and this a piece of data I obtained (the red dots are the precise points of contact, the thing that collided was a boxcollider onto the collider shown)

#

why do the three points stack like so? And why was there a repeating contactpoint (the one in the middle of the stack had a twin)

#

the better read I can get on how contactpoints behave exactly, the better code I can produce for it regarding platform collision and response

#

or, perhaps wait, I should first get my tile renderer to make all tiles square regardless of tile bitmap shape

#

my question still stands in curiosity though, thank you very much for your time

#

got a similar effect even with both being box colliders

#

is the first, outlier one usually the normal one?

#

like the first index sort of thing

#

kind of feels that way

copper blaze
#

is there a way to add select individual tiles for functionaity using unity's tilemap2d system?

brittle sparrow
#

you mean like, take a tile and give it a special behavior?

obtuse cedar
#

I'm making a roguelike and I would like to know a clean code approach to customizing aspects of the game.
such as if I have an ability that makes projectiles explode when it collides with something
would I put the explode on collision method into the base class of a projectile and enable it on the projectile object?

latent latch
#

Layer and collisional logic is fine for the top logical layer for something like a projectile controller.

brittle sparrow
#

i would put the explosion trigger on the projectile itself too

#

i'm not sure if it'd put the behavior script on the object itself though

#

i make lots of controllers

#

i use controllers for UI too

latent latch
#

if we're talking about rb collisional methods it would have to be on the object, otherwise you can sphere cast for collision/targets

hard viper
brittle sparrow
#

oh.. not sure at the moment, laptop's closed

#

but wait, it's always the default one

#

so whichever one that is

hard viper
#

then that is definitely wrong

brittle sparrow
#

ouch..

hard viper
#

because that is discrete

brittle sparrow
#

so continuous

#

i was so ready to pull out raycasts every frame

#

if that works idk

hard viper
#

discrete mode moves the hitbox and checks where it lands every frame, so you clip into the collider, and THEN it ejects you

#

continuous mode interpolates. is more expensive, but then you don’t get bullshit like what you are seeing now

#

you still want to do a bit of correction.

#

what I do is I take the point of contact, and the normal vector for that contact, and move a small bit into the tile collider (like contactpoint.normal * -0.05f)

#

then use that point to check for what tile you hit. Which I assume is what you are going for

#

then if the tile you find is null, check perpendicular to that point, on both sides slightly

brittle sparrow
#

will check later!

hard viper
#

just to make clear. red = point of contact. black = normal. green = moving -0.05f * normal from contact. If you don’t find a tile, move to check blue points, which is moving perpendicular to normal in both directions.

#

you need this because unity rounds positions like crazy, and your check WILL land on the very edge of a tile, and click the wrong thing, if you don’t correct.

#

the 0.05f is a const declared at the top. obvs

woeful furnace
#

Yo so im working on a geoguesser type game. Im storying the locations as a sprite and vector 2 + an id. These are stored as a scriptable object. There is a dictionary of these, Im struggling to get the length of the list and remove items from it.

hard viper
#

what list? you have a dictionary

woeful furnace
#

Im mean dictionary yea

lean sail
#

"storying the locations as a sprite and vector 2 + an id" makes literally no sense

hard viper
#

mydict.GetKeys.Length or something

woeful furnace
#

Its stored in a scriptable object

#

The dictionary is a dictionary of scripable objects.

hard viper
#

Dictionary<Vector2Int, SO> ?

lean sail
#

there is a Dictionary.Count if thats what you want

woeful furnace
#

Its not allowing me to do that.

lean sail
#

is someone physically stopping you from using this

hard viper
#

.Remove to remove a key

#

myDict.Count should get you the number of keyvalue pairs

woeful furnace
#

public Location[] locationdata;

#

This is how its stored

lean sail
#

that is not a dictionary

hard viper
#

that is not a dictionary

woeful furnace
#

I called it a list at first

hard viper
#

😂

woeful furnace
#

And you corrected me

hard viper
#

well it is not a list either

lean sail
woeful furnace
#

I dont know I dont spend all my day reading documentation with an anime pfp

#

I only use c# for unity.

hard viper
#

well, go learn about Dictionaries

woeful furnace
#

Im used to [] being a list

#

from python

hard viper
#

[] is an array

woeful furnace
#

List and arrays are practically the same.

hard viper
#

it’s like a list that can’t change size

#

do not mix up lists and arrays

leaden ice
lean sail
hard viper
#

arrays are fast as shit because you don’t need to manage them changing size, because they don’t change size

#

lists can change size, let you insert elements, search and sort easily, append/remove…

leaden ice
latent latch
#

im lazy so I use lists

leaden ice
#

This is just a matter of you thinking C# works like Python. It doesn't

hard viper
#

or a dictionary, depending on what you need

#

dictionary is like if you need the key to access the information to not be an integer

#

like if you want to connect a bunch of Vector2Int to LocationSOs

leaden ice
#

Python has dictionaries so hopefully they're familiar

#

Of course C# dicts are type safe 🙏

hard viper
#

LocationSO[] is an unchanging array of LocationSO to quickly access by order.
List<LocationSO> is a more flexible datastructure that can grow/shrink sort LocationSOs as you go along.

woeful furnace
#

Yea I really only use Python and typescript. For most of my stuff like Leetcode and the like so thats what im used to.

hard viper
#

Dictionary<Vector2Int, LocationSO> is an object where you put in a Vector2Int and it spits out a LocationSO that you assigned to it

woeful furnace
#

C# and c++ I do use but for unity and unreal so just messed up the syntax.

lean sail
#

Has anyone had values just randomly get completely jumbled, is there something I did that would cause this? Kinda lucky i even found where my error is quickly but my code is simply just

[SerializeField] List<Vector3> spawnPosition = new();
    void Awake()
    {
        if (spawnPosition.Count == 0)
        {
            Debug.LogWarning("No spawn points set");
            spawnPosition.Add(Vector3.zero);
        }
    }

the only other code just reads the value of spawnPosition
response.Position = spawnPosition[spawnPointIndex % spawnPosition.Count];

#

the values were originally like (0, 0, 0) (0, 15, 0) and something else i forgot

leaden ice
#

uhh except the top left and top right

#

which are very large negatives

#

show the rest of your code?

lean sail
#

yea those 2 were causing issues when i was trying to show someone my game 😆

lean sail
leaden ice
#

wondering if somehow the networking is involved 🤔

lean sail
#

id hope not because i didnt make it a network list, not even temporarily. Although now that i think about it.. i definitely never set this list to be anything in this scene thats causing issues

#

so maybe thats more of the issue

leaden ice
#

How are you setting the spawn points in the first place?

#

just in the inspector?

lean sail
#

im just typing them in rn yea

#

its just for testing purposes atm

leaden ice
#

what are theyu supposed to be?

lean sail
#

its where players spawn, so they all spawn in slightly offset positions from each other

#

oh yea wtf I checked another scene that I never opened after making that list and its the same issue

#

meh maybe unity is trying to grab some values that it thinks it has stored and is just filling it up with garbage. just happy i actually found it in a few minutes

copper blaze
#

is there a way to wipe all the tiles from a tilemap?

copper blaze
#

is there a way using the editor and not with calling a method during runtime?

leaden ice
fervent furnace
#

you should learn how to use tilemap palette to select large area

pure cliff
spring sand
#

Does anyone know if it's possible to customize the window's handler? (unsure if that's the name)

gloomy stirrup
#

its possible

#

I mean I never did it

#

but this may help you to get a idea

#

hope fully I find the video I watched randomly xD

spring sand
#

The full white thing lol

craggy veldt
#

here, a cut-down version of mine

    [DllImport("user32.dll")]
    static extern System.IntPtr GetWindow();

    [DllImport("user32.dll")]
    static extern System.IntPtr GetWindowStyle(
        System.IntPtr hnd,
        int idx
    );
 
    System.IntPtr hnd;
    const int _STYLE = -8;

    //get the default style
    int style = GetWindowStyle(hnd, _STYLE).ToInt32();

    //do whatever value to the style after
    //e.g Set(hnd, _STYLE, (uint)(style | someFlagsHere));
#

a bit messy, but oh well

tidal rapids
#

Hey guys I've got a weird issue for you all.

So basically I am working on an editor window that can upload some files to a backend when I click a button.

This all works fine but when I press the button the script runs and then gets stuck. It will only continue when I minimize Unity and reopen it, or click off of unity and back into it.

So if I click my upload button and then spam minimize and reopen Unity everything happens as it should, but when I click the button and just leave it the code will not run.

Any idea on what in the world might be happening?

ashen yoke
#

post code

tidal rapids
somber nacelle
#

!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.

tidal rapids
#
public void CreateLevel()
    {
        
        LootLockerSDKManager.StartGuestSession((response1) =>
        {
            if (response1.success)
            {
               

                LootLockerSDKManager.CreatingAnAssetCandidate(levelName, (response2) =>
                {
                    if (response2.success)
                    {
                        
                        UploadLevel(response2.asset_candidate_id);
                        
                    }
                    else
                    {
                        Debug.Log("Error asset candidate");
                    }
                }, null, null, null, id);
                Debug.Log("Successful");
                
            }
            else
            {
                Debug.Log("Not Successful");
            }
        });
        
    }

#
public void UploadLevel(int levelID)
    {
        string screenshotPath = "Assets/Screenshots/Level-Screenshot.png";
        LootLocker.LootLockerEnums.FilePurpose screenshotType = LootLocker.LootLockerEnums.FilePurpose.primary_thumbnail;
        

        LootLockerSDKManager.AddingFilesToAssetCandidates(levelID, screenshotPath, "Level-Screenshot.png", screenshotType, (screenshotResponse) =>
        {
            if (screenshotResponse.success)
            {
                

                string textPath = "Assets/Screenshots/Level-Data.txt";
                LootLocker.LootLockerEnums.FilePurpose textType = LootLocker.LootLockerEnums.FilePurpose.file;

                //AssetDatabase.Refresh();

                LootLockerSDKManager.AddingFilesToAssetCandidates(levelID, textPath, "Level-Data.txt", textType, (textResponse) =>
                {
                    if (textResponse.success)
                    {
                        LootLockerSDKManager.UpdatingAnAssetCandidate(levelID, true, (updatedResponse) => { }, null, null, null, null, id);
                        Debug.Log("Level Data Uploaded!");
                        //AssetDatabase.Refresh();
                    }
                    else
                    {
                        Debug.Log("Error Uploading Asset Candidate");
                    }
                });
            }
            else
            {
                Debug.Log("Error Uploading Asset Candidate");
            }
        });
    }

#

This all works it just requires me to unfocus and refocus back into unity

ashen yoke
#

try move it all into UnityEditor.EditorApplication.delayCall

tidal rapids
#

I move it into this?

#

or call this

ashen yoke
#
if(GUI.Button())
  EditorApplication.delayCall += CreateLevel(); // or whatever starts the whole call chain
tidal rapids
#

Thank you let me try this

tidal rapids
#

it doesnt seem to like that

ashen yoke
#

sorry, remove the ()

#

+= means add this method to the delegate invocation list

tidal rapids
#

gotcha

#

It doesnt seem to have worked

ashen yoke
#

show the button code

#

where you handle press

tidal rapids
#

    private void OnCustomButtonClick2()
    {


        EditorApplication.delayCall +=  CreateLevel;
       
    }

ashen yoke
#

uitk

#

no clue then

tidal rapids
#

Well thank you for trying to help I appreciate it

#

Anyone else have any idea?

timber cloak
#

Currently I try to generate a map but when i place it out i get this result, but when i in the code switches the places on the x and z cordinates and rotate each plane 180 degress the correct result is show, why and how do i fix it

brittle sparrow
#

I'm stumped.. I raycast with two vectors on the same x-axis, but they somehow end up contacting a certain boxcollider on a different x-axis point. This "boxcollider" is actually a tilemap that adopts a collider of a perfect box shape, and the raycast is a fairly small one; it occurs every frame. The raycast checks between two points, the position of the player in the previous frame, and the position of the player in the current frame. This position isn't the center of the player however, it's offset to the player's feet. And the weirdest part is that this bug never occurs when the raycast is done on a certain "platform" tile.

Here are some logs of the player's raycast failing, where the first and second vectors are the raycast points, the third vector is the player's actual position (not much purpose to it), and the fourth vector is the point at which the raycast hit (and it should've been the same as the two points being raycasted, but it somehow isn't..)

#

this might serve as a nice diagram showing the raycast

#

for exposition, the raycast is always small changes as the player is falling

orchid bane
#

Can word back-end be applied to the insides of a game or only to a web site?

gloomy stirrup
#

https://paste.myst.rs/hflqgjsc ... this code has no errors on compilation but when I hit the button which has OnFIre()... then it shows this :-

#

WHY ?

ashen yoke
#

ie with unity the front end would be your game code and backend would be the native engine code

#

but its arguable, and subjective

#

depends on the domain

inner slate
#

Hello, does anyone know the function in order to perform a cooldown before being able to perform an action again?

brittle sparrow
#

It depends on the framework you made for your game, if your question is on coroutines then i have no idea

#

i use cooldowns that update per-frame instead of threading/coroutines not sure what their difference is

inner slate
#

Okayy thx

brittle sparrow
hidden parrot
#

Line 25

gloomy stirrup
#

the target\

#

but I am defining it with target = GameObject.FindWithTag("Player");

#

then also its a problem

hidden parrot
#

Then it's not finding an object with that tag

#

Are you sure the object you want is tagged and that its exactly "Player"

gloomy stirrup
#

yes

#

what to do ?

hidden parrot
#

You're sure target is null?

#

And it's not rb?

gloomy stirrup
hidden parrot
#

Howd you check it, debug?

gloomy stirrup
gloomy stirrup
#

it hsows error

#

jand ik thats has to shwo error

#

but idk how to do it corrcetly

hidden parrot
#

Put a DebugLog the line after you set target and see if the debug log returns null or not

gloomy stirrup
#

like ?

hidden parrot
gloomy stirrup
#

ok

#

Vortex (UnityEngine.GameObject)
UnityEngine.Debug:Log (object)
commonpower:OnFire () (at Assets/Main Assets/Scripts/PlayerScripts/Commonpower.cs:20)
UnityEngine.EventSystems.EventSystem:Update () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:530)

hidden parrot
#

Okay, target isnt null.

trim schooner
gloomy stirrup
#

ahem

hidden parrot
#

oh im sleepy as hell thats obvious yeah

gloomy stirrup
#

such a silly mistake

#

wow not it has no errors but not going towards objects tagged as player

trim schooner
#
public Rigidbody projectilePrefab;

rb = Instantiate(projectilePrefab, transform.position, transform.rotation);
gloomy stirrup
#

which line

#

you saying to update the start or onfire ?

trim schooner
#

have a think about it, logically

gloomy stirrup
#

it just lauches it in random direction when i click button and then after fisrt time whenever I click it shows rigidbody is destoryed but you are still trying to acces it

#

is there anything specific that contains all the major funtions and feature of C# ?

#

and unity as well

#

I litraly spend whole day on a single script ;-;

#

instead I should stop making games and learn all that first

#

is there any source ?

mellow sigil
#

Going through individual features is probably not the most efficient way of learning. Take a course like the ones in !learn 👇 and make sure you understand each lesson before continuing to the next one

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/

gloomy stirrup
brittle sparrow
#

After gathering some more data, I decided to describe the issue above anew. The diagrams will do most of the explaining, but basically, I'm performing a raycast which is supposed to be a straight line, but it ends up hitting a point that's outside of the actual raycast line. The diagram with the banana cat shows the red line segment as the raycast (which goes in the up direction), the yellow dot which is supposed to be the ideal hit point, and the blue dots which are the approximate positions i actually end up getting rather than the ideal yellow position. I can prepare the code too if needed

#

The logs above show the respective vector2s: the top point of the red segment, the bottom point of the red segment, the blue point it ends up becoming, and the length of the red segment.

#

The logs show that, when the blue point ends up on the same y point as the desired yellow point, so y=-2.5, the x point ends up shifting. The opposite holds true, when the x point is as desired, the y point ends up shifting as well

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 sigil
brittle sparrow
# steady moat !code

i was thinking it could be some collider issue, but yeah i'll show some code too

#

thank you for helping

hard viper
#

did you change your rigidbody to continuous mode?

brittle sparrow
#

The second definition of Raycast in the second image is used, the first definition of Distance is used, according to the logs the vectors used in the Raycast function match the described issue

hard viper
#

raycasts stop when they hit a target, so if it is inside a collider, then that is just where it started

gray mural
brittle sparrow
#

oh, so if i call from inside a collider and go outside of it

hard viper
#

yeah that shit won’t work

brittle sparrow
#

then it breaks?

gray mural
brittle sparrow
#

i probably won't need to raycast from inside if i fix it to be so, but what if I had to call from inside?

gray mural
#

what

gray mural
#

I forgot

#

it won't detect collider if it starts inside it

brittle sparrow
#

fingers crossed, hope this works

hard viper
gray mural
#

oh

#

we are talking about 2D 💀

brittle sparrow
#

no good.. i started raycasting from outside the collider, but it still produces the same results; it either shifts from the desired x position or it shifts from the desired y position

#

it's always inside the collider too, never shifts the y going up

brittle sparrow
#

oh, what that sounds amazing

#

good job unity

#

strangely enough, drawline doesn't work..

#
Debug.DrawLine(Vector3.zero, new Vector3(0f, 5f, 0f), Color.red, 60f);

even using this as an example

#

maybe it's behind everything esle?

#

else**

steady moat
#

Do you have gizmos enabled ?

swift falcon
#

Hello. I got this issue with angles - while trying to obtain them for vector (origin in center) placed on 3d - I got position and length of vector3. But when try to calculate angles from heres formula it just keep changing vertical angle when moving in horizontal motion... https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates

In mathematics, a spherical coordinate system is a coordinate system for three-dimensional space where the position of a point is specified by three numbers: the radial distance of that point from a fixed origin; its polar angle measured from a fixed polar axis or zenith direction; and the azimuthal angle of its orthogonal projection on a refere...

brittle sparrow
#

oh

#

i feel

brittle sparrow
#

the drawline is only called when the ground is detected, I held space, these are the results

#

the y fluctuation isn't noteworthy, but the x shifts

steady moat
#

Then, your ray is wrong.

#

That means the entry data is just not correct

brittle sparrow
#

I logged it, i might have some logs

steady moat
#

Also, you might want to start your ray cast higher

brittle sparrow
#

start it higher?

#

maybe

steady moat
#

There is no way I take the time to analyze positions.

#

Yes, otherwise it start almost on the ground

brittle sparrow
#

praying this works

steady moat
brittle sparrow
#

is 0.1 position a good starter? the cat is 1.5 units tall

#

or should I do 0.3

#

i'll just try one or the other

#

oh, circlecast?

#

Alright, i found some very vital information

#

I did a raycast on vectors (0, -2.4) and (0, -2.6) and hitting the collider from outside, and it properly went to (0, -2.5)
Then, I did a raycast on vectors (0, -2.475) and (0, -2.523), pretty random y values. Still went to its proper (0, -2.5)
And then when I did raycast on vectors (2.354, -2.475) and (2.354, -2.523), the x position finally broke. This has to do with how precise Unity can be, and maybe this can't be avoided. I'm hoping I can still ground my character somehow without the unrelated x value changing unnecessarily

#

or, if it's not Unity's raycast method that's not being precise, I should look back at some functions of mine

#

I doubt they break anything though

#

yeah, my raycast function just passes the vectors as I call them

steady moat
#

I really doubt that Unity would not give you a point on the line you casted.

#

Really, really doubt it.

steady moat
brittle sparrow
#

yeah, is that where I went wrong?

#

yikes

steady moat
#

No, you need to use it.

brittle sparrow
#

oh

steady moat
#

But because you just are giving some fragment of code

#

We cannot see it.

brittle sparrow
#

i could send the whole related code, but it's sort of long

steady moat
#

You should just isolate everything.

brittle sparrow
#

lots of unrelated code in the files too

leaden ice
brittle sparrow
#

is github also okay?

swift falcon
leaden ice
#

yes

brittle sparrow
#

actually too lazy to set it up

steady moat
swift falcon
#

in need to find those two angles by knowing position and radius from center

steady moat
#

THen you have the forumla

#

There is nothing in Unity that will do that.

swift falcon
#

yeah but I writed it and it is not working

steady moat
#

Because you made a mistake or did not respect the assumption obvously

swift falcon
#
        {
            Vector2 anglesXY = Vector3.zero;
            Vector3 toSword = (_thisTransform.position - _rotateAroundPoint.position).normalized;
            float angleX = 0.0f, angleY = 0.0f;
            angleX = Mathf.Atan(Mathf.Sqrt((toSword.x * toSword.x) + (toSword.y * toSword.y)) / toSword.z) * Mathf.Rad2Deg;
            if (toSword.z < 0.0f)
            {
                angleX = angleX * Mathf.Deg2Rad + Mathf.PI;
            }
            anglesXY = new Vector2(angleX, angleY);

            return anglesXY;
        }```
#

for horizontal

brittle sparrow
#

alright should be good

#

hope this code is enough, there are a bunch of dependencies and weird looking functions but just assume they work

steady moat
brittle sparrow
#

Obj().xypos() is the Vector2 of the player

swift falcon
#

angleX is delta angleY is phi

steady moat
#

You might want to use Atan2

swift falcon
#

oh really

steady moat
#

Yeah

swift falcon
#

how do that ?

#

I mean , what is the second argument?

steady moat
#

This is the division

#

You have the upper as the first, and the lower at the second

#

Tht would be Mathf.Sqrt((toSword.x * toSword.x) + (toSword.y * toSword.y)) and toSword.z

swift falcon
#

and the lower one ?

steady moat
#

toSword.z

swift falcon
#

angleX = Mathf.Atan2(Mathf.Sqrt((toSword.x * toSword.x) + (toSword.y * toSword.y)) / toSword.z, toSword.z) * Mathf.Rad2Deg;b like that ?

steady moat
#

No

#

Read documentation, if you cant figure it out, you have little hope to figure the rest.

swift falcon
#

thx

brittle sparrow
steady moat
#

3-5 lines maybe

brittle sparrow
#

i'll make a function that depicts the raycast breaking, without using any weird non-unity functions

#

that'll work right

#

The code is called every frame, and produces the above results

#

so yeah, seems like Unity's raycast somehow breaks

steady moat
#

Remove all collider of your scene except one

heavy wren
brittle sparrow
#

Even the colliders that aren't of layer "Physical"?

#

those shouldn't get contacted in the first place

steady moat
#

In fact, you should do an empty project

#

And reproduce the issue

brittle sparrow
#

as proof, when i removed the Ground collider, the raycast stopped detecting

#

so only the Ground is being detected

#

It's a tilemap collider if that helps

steady moat
#

Also, why are you using a negative distance ?

brittle sparrow
#

oh right

#

i fixed that when i got the logs

#

just pretend it's positive

#

renewal

steady moat
#

And, why are you setting the direction as 2.354f, -2.523f

#

And plz !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.

steady moat
brittle sparrow
#

ohh, so the unity function breaks because the direction function is supposed to be simplified as much as possible?

steady moat
#

It should be Vector2.down

brittle sparrow
#

direction variable**

#

thing is, my raycast is supposed to check between the position of the player in the previous frame, and the position in the current frame. If the player were to be moving, the down raycast wouldn't really work in this scenario

steady moat
#

This is your ray at the moment

#

So, it is normal that you have a shift in x

#

That is why you should use Debug.DrawRay

brittle sparrow
#

actually, it's something like this

#

oops ended up being small

steady moat
#

It is not

brittle sparrow
#

there

steady moat
#

Impossible to be that

#

And this is not Debug.DrawRay

brittle sparrow
#

i could show it on debug.drawray

steady moat
#

Yes, do it

#

With the simple function you have

brittle sparrow
#

okay, i'm going to go through the whole process but i'm having this feeling you may be right

#

my genius was using Debug.DrawLine BocchiDead

steady moat
#

It was not reading the function signature you were using*

brittle sparrow
#

okay, I screwed up, I'm making a solution, praying this works, sorry about this

#

basically I assumed "dir" was just a second position i could put and the raycast function would figure out the direction it'll take

#

it was the other way around

heady iris
#

raycast has a lot of arguments in surprising positions

#

some of which are type-compatible with other arguments

#

see: putting a layer mask into the range parameters by accident

brittle sparrow
#

oh god it's solved

#

my understanding of "dir" was warped

#

thank you simferoce, and sorry for wasting your time

#

never doubting unity's accuracy capabilities again

lament river
#

Does anyone have any ideas what may cause a build to get stuck in the unity splash screen (Unity 2021.3.20f1)? And soon after it stops responding. If I build it as a 'development build' it runs perfectly fine. But non-development builds gets stuck. Editor doesn't give any errors. Sometimes, randomly, I manage to run a non-development build just fine for one time. But if I try to relaunch (without building) it gets stuck every time.

jade phoenix
#

whats the least painful way of storing hardcoded rhythm game levels

primal wind
#

There's no universal way, especially considering how diverse the gameplay of rythm games is

buoyant mural
#

bro it's been too many days i've been tryna get the sun to work fine I asked chatgpt everything and everything i tried nothing fixes the sun snapping between local rotation the readable inspector one idk what's the cause, currently my lines are like this I tried every rotation method

        float targetRotation = ((currentHour - 6) * 15) + (currentMinute * 0.25f) + timeLeftForNextMinuteNormalized;
        sun.transform.localRotation = Quaternion.Euler(targetRotation, sun.transform.localEulerAngles.y, sun.transform.localEulerAngles.z);```

For Testing i made value above 90 and it glitches
jade phoenix
#

i think it's been universally agreed upon that chatgpt isnt reliable for any kind of API library

buoyant mural
#

well

brittle sparrow
jade phoenix
#

no

#

hardcoded as in we're manually entering when every note/beat spawns in and i want to find the least painful system to store that information for some other people in the project to use when level designing

#

was thinking of using a json file but even that is pretty tedious work

brittle sparrow
#

oh, like in a text file?

#

yeah, just use text files

#

just copy what osu does

#

osu does it pretty well

#

the json system might take a tiny bit of work but it's all worth it in the end

#

but since osu uses milliseconds instead of music sheet BPM position sort of stuff, might be better to switch it up just a little bit

brittle sparrow
#

an example of an osu map file

buoyant mural
brittle sparrow
#

you could still use the millisecond system if you have some nice little bpm calculator next to your workspace

ashen yoke
brittle sparrow
#

you could make a whole new project to make it simpler

ashen yoke
#

yes ofc

#

start with the tool

#

timeline, events, etc

#

you can make it as web in js

brittle sparrow
#

yeah that works right

buoyant mural
jade phoenix
#

so ig

#

poor teammates what an L

brittle sparrow
#

json files are pretty easy when you get used to how they work

#

string splitting, temporary string variables

ashen yoke
#

you should not have to ever look at it

#

only when fixing some bugs with your serialization

jade phoenix
#

would it be easier to use ints or to use "1,0" and split it at load?

ashen yoke
#

you are starting it backwards and as a result with end up in some strange place, code and design wise

jade phoenix
#

wdym by starting it backwards?

ashen yoke
#

you should not care about json or any serialization format until you make the tool that produces those levels in memory first

surreal valve
#

How would I teleport the Player to another GameObject?

ashen yoke
#

then all you have to do is serializer.ToJson(level) and not care how it looks in text

jade phoenix
surreal valve
jade phoenix
ashen yoke
#

start with the tool

ashen yoke
#

similar to unity animator, or any timeline based ui

#

make it work from memory first

jade phoenix
#

the "timeline" should just be 1 list per bpm of the song, all songs at 100bpm

ashen yoke
#

or at least as some scriptable

ashen yoke
static matrix
#
 start:
        List<Tile> AdjTiles = TileOn.GetAdjacentTiles();
        Tile TryTargTile = AdjTiles[Random.Range(0, AdjTiles.Count)];
        if (TryTargTile)
        {
            if (TryTargTile.IsWater)
            {
                goto start;
            }
            else
            {
                return TryTargTile;
            }
        }
        return TileOn;

is there a reason why this code always favors tiles to the right and up??? Its not that the creatures only move in those directions its that over time they all migrate to the right of the map

ashen yoke
#

design it, plan it, make it, game will run levels from scriptables, then you can serialize them as any format

brittle sparrow
buoyant mural
#

set the teleportLocation var in the unity editor

jade phoenix
static matrix
#

maybe I should forgo random movement and switch to targeted movement

brittle sparrow
static matrix
#

is it a psudorandomness issue?? or is it something else

lusty zephyr
buoyant mural
#

ye

#

what's with the kills tho

#

I thought he jus asked how to teleport lol

lusty zephyr
buoyant mural
#

oh

#

I mean setting a vector in the inspector is harder than jus a gameobject 💀

lusty zephyr
#

then you don't need to forget to reset the kills or disable the function @surreal valve.
If you don't, then the player will keep on teleporting to the position each frame per second.

buoyant mural
surreal valve
buoyant mural
#

also why do you have [SerializeField] and the variable is public?

lusty zephyr
surreal valve
buoyant mural
#

or make the player spawn +2 above the object's Y axis

lusty zephyr
lusty zephyr
# surreal valve Good catch

np. You will bump into those things if you forget it. Might have saved a 10 minute research of why the player isn't moving anymore after teleporting.

buoyant mural
#

Since you cant set a local rotation above 90 I tried:

        sun.transform.localRotation = Quaternion.Euler(0f, sun.transform.localEulerAngles.y, sun.transform.localEulerAngles.z);
        sun.transform.Rotate(targetRotation, 0f, 0f);``` tho for some reason it's rotating around the Y axis instead
#

But setting to 0 then rotating will prolly mess up the code

#

so idk what to do at this point

orchid bane
#

When I create a class by serializing it in editor its constructor isn't called, how to bystep it?

steady moat
static matrix
#

I know i know

#

I feel evil every time I use goto

steady moat
static matrix
#

what does the ? do? ive seen it a few times but never used it myself

nova moon
nova moon
lusty zephyr
static matrix
#

cool

jade phoenix
#

so i'm guessing that when i build my rhythm game, i'll want to have all the maps saved in a folder in Application.dataPath, but how can I access that to throw manual data in there?

#

or do i just keep a folder in the Assets directory of my json files?

leaden ice
# jade phoenix so i'm guessing that when i build my rhythm game, i'll want to have all the maps...

If you want to access json files at runtime:

I don't see Application.dataPath as being useful here

ashen yoke
jade phoenix
#

or do i just create one and assume it gets correctly transferred over to the assigned path on build

leaden ice
copper blaze
copper blaze
leaden ice
#

Anyway if you want you can just make a quick editor script to call the function in the editor

copper blaze
#

i misread your answer

vague token
copper blaze
leaden ice
vague token
leaden ice
copper blaze
#

also unity already has RigidBody component with gravity if you want to use that

leaden ice
#

you want gravity to happen all the time right?

#

You should be running that stuff in Update

vague token
#

I will try it

jade phoenix
leaden ice
jade phoenix
#

I have.

leaden ice
#

then what part are you confused about

jade phoenix
#

seems to me like both contents within Resources and StreamingAssets get copied to a reserve folder on the designated OS instead of getting turned to a binary file, allowing it to be accessed by a path

leaden ice
#

StreamingAssets files are copied verbatim over to the Application.streamingAssetsPath folder as regular files
Resources are packed into the game build as assets but are accessible via Resources.Load as assets

leaden ice
jade phoenix
#

so which one is preferred for holding json files

leaden ice
#

that's up to you

#

depends on your needs and what you're trying to do and how you want to access these files

jade phoenix
#

well which one is better for which scenario?

#

im guessing there's an added layer of security with Resources.Load

#

but I'm not all that worried about people messing with files

static matrix
#

I dont know what I did but I tweaked the code to try and make it so animals will only stay on their preferred tiles and somehow made it so it pathfound perfectly to the bottom of the screen
wait
im an idiot
maybe

#

I AMMM an idiot
i never set the tiles actual types

#

but still wierd that it pathfound normally
it went around some water at one point

surreal valve
#

"Object reference not set to an instance of an object" Line 20. I have the player in the scene with KillTracker attached. What do?

brittle sparrow
#

I tried searching this up, but nothing came up, not sure if this channel is suitable for this question, but I wanted to use the same Physics Shape that a sprite uses, but for many sprites. I'm thinking of some sort of copy and paste method, but I'm unable to copy or paste any data from one Sprite Editor to another unfortunately. Any ideas? Thank you very much for your time.

#

this sort of stuff

static matrix
#

they are migrating southeast

tribal ginkgo
static matrix
#

this is wierd

tribal ginkgo
static matrix
#

true, although sometimes it is required,
besides, they are probably just starting out, so lets answer their question and then help them improve their code

static matrix
#

unless you setup your vars to be green

#

i see
huh
they always migrate in the direction first in the getAdjacency script

jade phoenix
#

JsonUtility only accepts a string path to load from a file. how do i do this with something i grabbed from Resources.Load(), which provides a TextAsset ?

vague token
#

why does my cube look so 2d

#

right screen

rigid island
vague token
#

oh I see

#

thx alot

jade phoenix
#

i love orthographic camera

#

its addicting

rigid island
jade phoenix
#

im not sure.

jade phoenix
#

does StreamingAssets actually give me a path?

rigid island
static matrix
#

this is exceptionally odd

jade phoenix
#

i just want an easy way of loading json files into a class like how JSONUtility can

#

the files are extremely small

rigid island
#

anything you put in there could be potentially loaded in

leaden ice
jade phoenix
#

both

leaden ice
#

Use StreamingAssets for your edit time stuff and then just designate a folder somewhere for the runtime stuff

jade phoenix
#

and when i build to mobile, that folder will transfer over correctly and still be accessible the same way?

rigid island
#

Application.persitentDataPath should be able to be cross platform

jade phoenix
#

i'd just need to change this when i build it yeh?

rigid island
#

dataPath is not what you need iirc it should be persitentDataPath

jade phoenix
#

oh that's whats mentioned in the StreamingAssets docs

#

actually wait no im reading this wrong\

#

Application.streamingAssetsPath is what i need

rigid island
#

oh for streaming assets , tbh i've not used them too much

static matrix
#

oh thats why I removed the randomness which removed the randomness from direction too

jade phoenix
#

do i need to specify a file extension in the path

#

the docs dont say

static matrix
#

my computer does not like what I am doing to it

hasty haven
#

tfw you refactor a method to be faster but its not

leaden ice
#

if you want to use File.ReadAllText for example, that needs the full filename, yes

elfin tree
#

I'm drawing a ray that's supposed to aim at the big white cube thing. For some reason, it seems to point at a weird random location behind it, I also tried using .position instead of localPosition, what am I missing?

leaden ice
#

rays expect a position and a direction

elfin tree
#

ahhh..

leaden ice
#

if you want the direction from A to B you can get that with (B - A).normalized

#

e.g.

Vector3 directionToBuilding = (buildingPosition - currentPlayerPosition).normalized;```
heady iris
#

(or drop the normalization to get a vector that takes you from A to B)

leaden ice
#

yepo

heady iris
#

is there a better name for that

leaden ice
#

I would call that offsetToBuilding

heady iris
#

other than just "a vector"

#

maybe an offset, or a delta

leaden ice
#

yeah, offset, diff, delta

#

something like that

heady iris
#

i do usually call that kind of thing a "delta"

#

florpDelta

elfin tree
#

Not sure I get the last thing, but something like that seems good enough?

heady iris
#

what is the "last thing"?

#

normalizing it?

heady iris
#

B - A, added to A, takes you to B

#

B - A + A = B

leaden ice
#

since you're not using it

heady iris
#

yes, DrawRay doesn't actually take a Ray

elfin tree
#

true true, it's to calculate the distance

heady iris
#

the Ray type is a position and a direction

elfin tree
#

between player and building

leaden ice
heady iris
#

notably, a Ray doesn't have a length

heady iris
#

DrawRay takes a position and a delta and draws a line starting at the position

#

the line's direction and length are based on that delta

#

Debug.DrawRay(Vector3.zero, Vector3.right * 10) would draw a line from [0,0,0] to [10,0,0]

#

mildly annoying conflict between those two senses of "ray"

jade phoenix
#
    public SerializableLevel GetLevel(string levelName)
    {
        return JsonUtility.FromJson<SerializableLevel>(Application.streamingAssetsPath + "Levels/" + levelName);
    }```
leaden ice
#

well

#

actually

elfin tree
leaden ice
#

which is not right lol

#

you need to read the file

#
string json = FIle.ReadAllText(Application.streamingAssetsPath + "Levels/" + levelName);```
jade phoenix
#

oh when it says string json does that mean path or file s a text

leaden ice
#

literally a string

#

json string

jade phoenix
#

ah ok

heady iris
#

it would explicitly tell you if it took a file path

heady iris
#
Debug.DrawLine(ray.origin, ray.GetPoint(length));
#

e.g.

jade phoenix
leaden ice
#

but yes

#

btw recommend building your filepath like

string filePath = Path.Combine(Application.streamingAssetsPath, "Levels", levelName);```
heady iris
#
Ray ray = new Ray(Vector3.zero, Vector3.right);
Vector3 start = ray.origin;
Vector3 end = Debug.ray.GetPoint(10);
Debug.DrawLine(start, end);
jade phoenix
heady iris
#

is this VSCode

leaden ice
#

It should have auto suggestions

heady iris
#

i know it wouldn't import stuff for me, annoyingly

#

ah, no, there it is

#

It doesn't autocomplete the name if it isn't already available, so it tries to autocorrect it to some random nonsense

#

there might be a toggle for that somewhere, but I do prefer not getting 3,000 random things thrown at me, too :p

heady iris
#

That's pretty roundabout, of course

elfin tree
#

tyvm

static matrix
#

what the friiiiick
whyyyyyy

heady iris
#

you have shown us one line of code

#

i have zero idea what you're doing

jade phoenix
static matrix
#

im more complaining on the fact it called "Hey this thing is null" on the check for if it is null

#

ill just do if(target)

heady iris
#

Those are two completely different things, yes

leaden ice
heady iris
#

Target is null. You get an error.

static matrix
#

ah
because im asking if the child of the parent object that doesnt exist exists

heady iris
#

you're trying to ring the doorbell when the entire house is missing

#

there is no "child" here

static matrix
#

sorry wasnt sure how to phrase it

heady iris
#

Target is some unity object (presumably a MonoBehaviour). It has a property called gameObject

hexed pecan
#

A monobehaviour's gameObject is never null anyway (assuming that target is MB)

heady iris
#

gameObject will never be null on a valid MonoBehaviour

#

(maybe after it gets destroyed?)

static matrix
#

hold me im scared
hopefully this is just me being stupid and not a fundamental design flaw

heady iris
#

you will get lots of spiking in the editor

#

probably some mixture of garbage collection and expesnive UI updates

static matrix
#

i dont have any UI

heady iris
#

not your UI

#

the editor UI

static matrix
#

oh

#

I also didnt set my profiler background to blue

heady iris
#

you mean the tint when you're in play mode?

static matrix
#

no
the blue in the profiler is my script lag

heady iris
#

ah

#

well, then start analyzing it

static matrix
#

apparently its all coming from the linecasts for checking adjacent tiles for animals

#

which is bad
because rewriting that to not use linecasts is would be a hassle

heady iris
#

if you're just checking adjacent tiles, this sounds like a simple dictionary lookup

#

assuming this is a tile-based game where animals are always on a single tile

simple ridge
#

Hi everyone, I was wondering if there was a way to generate a direction vector using randomisation.

I have read that you can do Random.withinUnitSphere, however I want my new unit vector to be only a curtain specified angle off from a base direction. Think of it like you fire a gun in a direction and there is a chance for inaccuracy added to the ray cast of say 10 degrees from the true shot.

I know I can do this pretty easily by randomising some angle between 0 - 360 and then using that create a vector using some second randomisation for the angle of inaccuracy. But the problem is that the distribution of the points doing this will very heavily favour the center. So ideally I'm looking for a way of doing it with as equal distribution of points as possible.

heady iris
#

I'm not sure about getting a specific angle

#

but a very simple technique is to add a small random vector to a direction vector

#

then normalize

#

Ah, you know what: you could compute a Quaternion from random values, then apply it to the direction vector

static matrix
#

the issue is its procedural
hexbased

heady iris
#

I have no idea what that distribuiton would look like, thought.

heady iris
static matrix
#

yeah
ig I could just run it once, get all of them in a collection for each tile, and then not run it again

heady iris
#
Vector2 rand = Random.insideUnitCircle;
Quaternion.Euler(rand,x, rand.y, 0);
#

i'd have to actually test that to see what it winds up doing

#

oh that first line is very wrong lol

simple ridge
#

I feel that would also give a distribution heavily focused around the center, i did consider that though chose against it as I wouldn't have the same or close distribution to doing it using angles

heady iris
#

that's better

heady iris
hexed pecan
#

So are these vectors just directions or do they need differing lengths too?

heady iris
#

some kind of gaussian

heady iris
#

...how did I never realize you can just normalize that to get something on the circle

static matrix
#

you could always do onUnitSphere and then set the y?
although ig that could land inside the circle too

heady iris
#

(but is that gonna be uniform? if the original insideUnitCircle is uniform, then it should be fine)

simple ridge
#

The use case isn't actually for random spread, its just a bit harder to explain. Its for trajectory calculation where I will leave something running to calculate something but I need to test as many cases within a randomised set as possible, however if most of the directions are centered around the middle then I'll be repeating alot of trajectories (btw this isn't for runtime, I know this is a bad way of doing anything trajectory related in a game)

heady iris
#

if it's hard to explain then you need to think about it more

#

that still sounds like random spread to me :p

#

you're randomly adjusting a direction vector

simple ridge
#

Yes but its for calculating over 10,000 different vectors, if I'm looking for values on the outer rim its unlikely to find them if the distribution favours curtain directions

heady iris
#

well, two things

#
  1. you don't know what that distribution looks like yet
#
  1. you could always just make it non-random
#

note that doing that naively will give you a very strong bias towards the center

#

e.g. imagine picking points on a circle by choosing a radius and an angle

#

if you do r=0, 1, 2, 3, ..., 9, 10 and theta = 0, 15, 30, 45, ..., 330, 345, 360, you'll get more points close to the center

#

Randon.insideUnitCircle correctly gives you a uniformly random point inside a unit circle

#

a visualization of such a problem

pearl snow
#

Hi hi, I need quick help, I am trying to change a Polygon Collider "size" after launching a "growing" projectile
I used .points[i] += new Vector2(x,y) but it doesn't seem to work, I think I am missing something after the .points[i] ? but I am not sure

leaden ice
#

and that array is not tied to the collider

heady iris
#

easy mistake to make

leaden ice
#

you should:

  • copy the array into a local variable, one time
  • modify your array
  • copy your array back into the component
pearl snow
#

Okay hold up wait

leaden ice
#
Vector2[] points = collider.points;
for (blah blah blah) {
  blah blah
}

collider.points = points;```
heady iris
#

This is similar to a case that actually gives you an error

#

e.g.

pearl snow
#

okay I get it thank you I'll try

heady iris
#

transform.position.y += 3;

#

the compiler can catch that one

#

the problem is that the points array isn't a value type. It's ~possible~ that someone else has a reference to the array

heady iris
simple ridge
heady iris
#

although

#

i see

pearl snow
#

So what was doing my code before ?

heady iris
#

you want the angle between the original vector and the new vector

#

Vector3.Angle will do the trick.

simple ridge
heady iris
#

So, wrong one.

heady iris
#

You could probably figure it out from the Quaternion, but I'm not sure how off the top of my head.

#

Vector3.Angle(Vector3.right, Vector3.forward) ought to be 90

pearl snow
#

So basically I have 4 elements under the array, after making the copy of it, I can change the 3rd element by using points[2] for example ?

heady iris
#

you were modifying one element of that array

#

which did nothing to do the collider

pearl snow
#

Oh so basically by accessing the points on the collider I was making a copy ?

heady iris
#

store the array locally, modify it, and assign it to the collider's points property

pearl snow
#

Okay GG thanks it worked

#

Well new lesson learnt !

heady iris
#

unity objects use a lot of properties

#

a property calls a method when you access it, even though it looks and feels like a field

surreal valve
#

Why won't the NavMesh bake?

#

correction; it bakes but never creates an object

heady iris
#

there is no object

surreal valve
pearl snow
heady iris
#

perhaps you're thinking of the new component-based system?

#

where you add a NavMeshSurface to an object

surreal valve
#

yes

#

thank you

heady iris
#

the old system just stores it somewhere in the scene

#

very fuzzy

#

you'll need to install the "AI Navigation" package to use the new stuff

surreal valve
#

like this?

heady iris
#

i don't know what you've screenshotted here

#

this tab?

#

this is still part of the old system

#

afaik

surreal valve
#

the navmesh doesn't generate?

#

(I searched for navmesh in the scene)

steady moat
surreal valve
# steady moat

What do I do with this? It takes me to a github page containing a project

steady moat
#

Read the page

#

Also, it shows you that you are using a older version

heady iris
#

ah, it still points you to github, eh?

#

what version of unity is this?

pearl snow
#

I imagine if I wanna modify the offset of a Circle collider 2D I need to proceed the same as previously ?

swift falcon
#

What's the object for mesh subtraction? E.g. I subtract a circle of radius 5 from a circle of radius 6 and get a ring of radius 5 with length 1?

steady moat
swift falcon
#

I remember this in Godot, dunno about Unity

pearl snow
heady iris
steel finch
heady iris
#

but yes, you'll do something similar

#

although

#
collider.offset += Vector3.right;
surreal valve
pearl snow
heady iris
#

that works

#

if you want to play with the individual values, you'll need to create a copy.

#
var copy = collider.offset;
copy.y = 12345;
collider.offset = copy;
pearl snow
#

welp yeah I need to change it precisely

heady iris
#

Exact same reason. The compiler yells at you this time, though.

pearl snow
#

xD

heady iris
#

since it knows there's no way collider.offset.y = 0; makes any sense

pearl snow
#

good thing I haven't tried before asking

heady iris
#

collider.offset returns a value type, so nobody else could be referencing it (by definition)