#archived-code-general
1 messages · Page 161 of 1
Yeah but I need to do some kind of min max system cuz it may, or may not, need time compression or even stretching, but also with a clamped min and max
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?
Why min and max time. You know how much time it will take ?
I don't, the times are mutable, I have to pick the right value
There is just one outcome possible when all action has been chose doesnt it ?
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
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.
I guess there is no max, I can infinitely slow down anything, so its just mins right?
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
Not everyone is same time to complete their turn by default, but I want them all to stay in synch so anyone who is "too fast" I wanna slow down to match the slowest
hello I don't really understand, which class does this go in?
The child class
Read on polymorphism
So, it is not a turn by turn (tradional). Everyone plays their turn at the same time ?
Exactly yeh
But in synch cuz multiple turns can be "queued"
Then how could you make it works ? If anyone can just play whatever they want at anytime.
Player can click 3 squares over, which is 3 turns worth of movement, so every other entity will do 3 turns of actions
So, it is turn by turn. Everyone choose an action, then it is executed at the same time.
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
yup!
Then, you still know how much time it is going to take.
You can just normalize the time.
For every entities
Exactly
Then what is the issue ?
The tricky part is just that the player can do more than 1 move in 1 round due to auto attacks
This also is known
Doing the sort of shrink/grow math to make it fit
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
Why wouldnt it be ?
Mostly just trying to work the math out
You know how to normalize stuff don't you ?
I think it's all just min times and I just pick the slowest min time, theoretically
You divided all by the larger
But then maybe I still need a static const min time any given round can be?
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
I have tried everything i could think of including the answers in the forums to fix it but it still shows the same error
You just need to take care of that when you find the longest
In fact, you could even use this as the normal time.
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
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.
I had reimportet the same package 3 times and it magically fixed itself so fixed I guess
could anyone help?
when is faceDirections being declared and assigned?
and have you done anything to verify that it's actually raycasting in the way you expect?
i.e. using Debug.DrawRay
the dot product would be 1 if they were approximately aligned. But you likely want to do hit.normal not ray.direction
and a simpler way to check is like if (Vector3.Angle(hit.normal, Vector3.up) < 1)
if you're not using the hit normal I don't see the point of the raycast
ok I'll try both of your suggestions
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?
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
if the ground is flat, then a raycast perpendicular to the ground's normal vector will never hit it
it can rotate and still be laying on the floor. it's a cube so on different sides
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
ok so compare the angles of each side with vector3.up
I don't see what the raycast is for
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?
!code please that is unreadable
📃 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.
sorry, here you go!
https://hatebin.com/iqzqqrifvw
ur using intialTerrainPos.x for both the X and Z coord
not sure if that might be causing the gap
that was exactly it, tyvm!
np
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 :)
either Teams Teams[index] or Teams[index].Players is null
you have to figure out which
you can attach the debugger or use Debug.Log
I have
and?
none of them seem to be
let me check again
and what the results were
alr
oh wait
i think i may be stupid
dont i have to initialize the list by using the code
= new List<TYPE>()
._.
yes that will be necessary if the list isn't being serialized by Unity
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
I installed the official newtonsoft json package, but in vscode it flags using Newtonsoft.Json; as an error?
Regenerate project files
Also if you're using assembly definitions don't forget to reference the assembly
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)
Show code
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
I wouldn't recommend it xD
Fixed my problem - I'm an idiot.
2 days of troubleshooting and I forgot to add the code under the correct switch case 🥲
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
direction implies that it isn't a position. What you're providing it above aren't directions but positions.
? in which part
Every call to GetAdjacency(...) above.
Direction would be target position minus initial position.
oh, that gets the adjacent tile in the provided direction
Not initial position plus offset. This would only yield another position.
its a linecast, not a raycast
I named it poorly, it should be endpos
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.
about that
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
example of all the things going right
(Yellow dots)
click, select none
scroll up
do you see "none" now?
could you just set the reference on the instance after you retrieve it from the pool, assuming you have both the prefab and instance refs at that point?
oh yea i guess i could lol idk why I didnt think of that
it would be nicer to have unity do it for you but i think it'll always "fix" direct serialized refs
yea understandable, itd probably be way more of a pain if it didnt assign the reference tbh
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
any thoughts on why this 9 sprite is rendering so weird on the canvsas? Is it cut correctly? Thank you!
#📲┃ui-ux (this is a programming channel)
ok thank you
CooldownToString((double)86405.0f)
TimeSpan.FromSeconds((double)86405.0f).ToString()
(double)90061.0f)
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
it was just to show how this code works
probably exit time on the transition. but #🏃┃animation
@stark nimbus did you take time to read the article I sent ?
yes, I know how .ToString() format methods work, for both TimeSpan and DateTime
And, you know that you can format them ?
yes.. and which one does this?
TimeSpan ts = new TimeSpan(3, 42, 0);
Console.WriteLine("{0:%h} hours {0:%m} minutes", ts);
// The example displays the following output:
// 3 hours 42 minutes
it still doesn't make my code any different, other than replacing left += passed.Hours with left += $"{0:%h}", or left += passed.Minutes with left += $"{0:%m}", etc...
It is a 1 liner
I mean, you did ask for how to SIMPLIFY it. And those changes don't make it functionally different, just MUCH simpler
there would be no left +=
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
The whole thing would be something like left = "{0:%d} day, {0:%hh} hour, {0:%m} minute, and {0:%s} seconds";
hi can any of you help me with sum
that would show "1 day, 0 hours, 0 minutes and 1 second"
its unity related not much code related if thats ok
you can make them conditional
Don't cross-post
ok sorry
I thought there would be a ToString format that would do exactly what I want, but apparently not
I see, then no, I am afraid there is no huge difference that you can do. Except maybe using string interpolation https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
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
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.
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
How to post !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.
📃 Large Code Blocks
Large code blocks should be posted as links to services
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
that was exactly it. thank you
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
I did make an attempt with an Array yesterday, and then with an int that I would increment or decrement
but this is much better
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
Try changing the mesh's indexFormat to UInt32
(it may not work, it's just a hopeful guess)
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
is there a way to add select individual tiles for functionaity using unity's tilemap2d system?
you mean like, take a tile and give it a special behavior?
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?
Layer and collisional logic is fine for the top logical layer for something like a projectile controller.
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
if we're talking about rb collisional methods it would have to be on the object, otherwise you can sphere cast for collision/targets
i had this exact same issue. is the rigidbody of the thing colliding with the tilemap set to Continuous or discrete mode?
oh.. not sure at the moment, laptop's closed
but wait, it's always the default one
so whichever one that is
then that is definitely wrong
ouch..
because that is discrete
so continuous
i was so ready to pull out raycasts every frame
if that works idk
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
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
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.
what list? you have a dictionary
Im mean dictionary yea
you should probably take a moment and rewrite what you just wrote
"storying the locations as a sprite and vector 2 + an id" makes literally no sense
mydict.GetKeys.Length or something
Its stored in a scriptable object
The dictionary is a dictionary of scripable objects.
Dictionary<Vector2Int, SO> ?
there is a Dictionary.Count if thats what you want
Its not allowing me to do that.
can you specify...?
is someone physically stopping you from using this
that is not a dictionary
that is not a dictionary
I called it a list at first
😂
And you corrected me
well it is not a list either
you literally wrote dictionary of these
I dont know I dont spend all my day reading documentation with an anime pfp
I only use c# for unity.
well, go learn about Dictionaries
[] is an array
List and arrays are practically the same.
In python yes. In C# no
you really should specify what you actually want to do, because i still have no clue if theres even a problem
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…
You cannot "remove" items from an array. If you want that functionality, use a List
im lazy so I use lists
Ill do that
This is just a matter of you thinking C# works like Python. It doesn't
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
Python has dictionaries so hopefully they're familiar
Of course C# dicts are type safe 🙏
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.
Yea I really only use Python and typescript. For most of my stuff like Leetcode and the like so thats what im used to.
Dictionary<Vector2Int, LocationSO> is an object where you put in a Vector2Int and it spits out a LocationSO that you assigned to it
C# and c++ I do use but for unity and unreal so just messed up the syntax.
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
all of those numbers are essentially 0
uhh except the top left and top right
which are very large negatives
show the rest of your code?
yea those 2 were causing issues when i was trying to show someone my game 😆
most of the code is unrelated. its for spawning in multiplayer, spawnPosition is only used in the sample i showed
https://pastebin.com/ZyGQQW2d
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
wondering if somehow the networking is involved 🤔
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
what are theyu supposed to be?
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
is there a way to wipe all the tiles from a tilemap?
is there a way using the editor and not with calling a method during runtime?
couldn't you just Reset the tilemap?
you should learn how to use tilemap palette to select large area
Hey we got that
(a, b) = (b, a)
Now!
Does anyone know if it's possible to customize the window's handler? (unsure if that's the name)
that full white thing or just the name and logo ?
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
The full white thing lol
you can use the native api in user32.dll. You can use dllimport for this. Assuming what you want is windows only
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
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?
post code
!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.
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
try move it all into UnityEditor.EditorApplication.delayCall
if(GUI.Button())
EditorApplication.delayCall += CreateLevel(); // or whatever starts the whole call chain
Thank you let me try this
Why is += used here?
it doesnt seem to like that
private void OnCustomButtonClick2()
{
EditorApplication.delayCall += CreateLevel;
}
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
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
Can word back-end be applied to the insides of a game or only to a web site?
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 :-
a powerful website for storing and sharing text and code snippets. completely free and open source.
WHY ?
to anything that has logical front and back
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
Hello, does anyone know the function in order to perform a cooldown before being able to perform an action again?
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
Okayy thx
anyone ??
To add on to this quandary, I notice two abnormalities. When raycasting on the platforms, the y-axis is always different. When raycasting on the dirt blocks, the x-axis always shifts by a random amount.. here are their respective render and collider shapes
the target\
but I am defining it with target = GameObject.FindWithTag("Player");
then also its a problem
Then it's not finding an object with that tag
Are you sure the object you want is tagged and that its exactly "Player"
yes
Howd you check it, debug?
well I didnt added rigid body to projectileprefabs... but after adding it it shows the same error
I cant.. when i write if(target = GameObject.FindWithTag("Player")
it hsows error
jand ik thats has to shwo error
but idk how to do it corrcetly
Put a DebugLog the line after you set target and see if the debug log returns null or not
like ?
Debug.Log(target);
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)
Okay, target isnt null.
1- It should be Start() not start() so this method won't get called
2- The rb that you get in Start() isn't the rb that is in the scene when you Instantiate the prefab in OnFire() on line 19
ahem
oh im sleepy as hell thats obvious yeah
such a silly mistake
wow not it has no errors but not going towards objects tagged as player
public Rigidbody projectilePrefab;
rb = Instantiate(projectilePrefab, transform.position, transform.rotation);
have a think about it, logically
ok
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 ?
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
🧑🏫 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/
ok thanks
what you did to learn it ?
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
!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.
I already knew programming beforehand so it's not really applicable to you. A combination of Unity Learn courses, more advanced tutorials and reading the documentation
oh ok
i was thinking it could be some collider issue, but yeah i'll show some code too
thank you for helping
did you change your rigidbody to continuous mode?
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
raycasts stop when they hit a target, so if it is inside a collider, then that is just where it started
oh, so if i call from inside a collider and go outside of it
yeah that shit won’t work
then it breaks?
it will be called if you call it inside the collider
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?
what
oh, it won't be detect
I forgot
it won't detect collider if it starts inside it
fingers crossed, hope this works
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
Can you use Debug.DrawRay ?
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**
It will not be.
Do you have gizmos enabled ?
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...
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
I logged it, i might have some logs
Also, you might want to start your ray cast higher
There is no way I take the time to analyze positions.
Yes, otherwise it start almost on the ground
praying this works
And, you might want to use https://docs.unity3d.com/ScriptReference/Physics2D.CircleCast.html
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
I really doubt that Unity would not give you a point on the line you casted.
Really, really doubt it.
And also, do you use ray.point ?
No, you need to use it.
oh
i could send the whole related code, but it's sort of long
You should just isolate everything.
lots of unrelated code in the files too
use a paste site
is github also okay?
How to use quaternions to calculate angles in spherical cooridante system ?
yes
actually too lazy to set it up
Not exactly sure. I though you wanted a euler angle from a vector.
https://en.wikipedia.org/wiki/Spherical_coordinate_system#Coordinate_system_conversions those i need
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...
in need to find those two angles by knowing position and radius from center
yeah but I writed it and it is not working
Because you made a mistake or did not respect the assumption obvously
{
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
alright should be good
hope this code is enough, there are a bunch of dependencies and weird looking functions but just assume they work
I'm not seeing any delta nor phi.
Obj().xypos() is the Vector2 of the player
angleX is delta angleY is phi
You might want to use Atan2
oh really
Yeah
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
and the lower one ?
toSword.z
angleX = Mathf.Atan2(Mathf.Sqrt((toSword.x * toSword.x) + (toSword.y * toSword.y)) / toSword.z, toSword.z) * Mathf.Rad2Deg;b like that ?
No
Read documentation, if you cant figure it out, you have little hope to figure the rest.
thx
it might be a long read, but it should contain everything
Replicate your issue in 1 function.
3-5 lines maybe

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

Remove all collider of your scene except one
@quartz folio That worked and it makes so much sense because it looked like the mesh was reusing indexes and I didn't know this property existed. Thank you!
Even the colliders that aren't of layer "Physical"?
those shouldn't get contacted in the first place
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
Also, why are you using a negative distance ?
oh right
i fixed that when i got the logs
just pretend it's positive
renewal
📃 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.
ohh, so the unity function breaks because the direction function is supposed to be simplified as much as possible?
It should be Vector2.down
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
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
It is not
i could show it on debug.drawray
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 
It was not reading the function signature you were using*
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
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
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
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.
whats the least painful way of storing hardcoded rhythm game levels
There's no universal way, especially considering how diverse the gameplay of rythm games is
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
i think it's been universally agreed upon that chatgpt isnt reliable for any kind of API library
well
by hardcoded, you mean you contain the rhythm game levels inside your code?
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
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
tedious how?
an example of an osu map file
when I made it forced as 91 it goes 89 a frame and 91 another frame
you could still use the millisecond system if you have some nice little bpm calculator next to your workspace
you think anyone edits that by hand?
oh, then idk make an editor like osu has
you could make a whole new project to make it simpler
Tried using Transform.rotate but fixed nothin
this was my idea
so ig
poor teammates what an L
json files are pretty easy when you get used to how they work
string splitting, temporary string variables
you should not have to ever look at it
only when fixing some bugs with your serialization
would it be easier to use ints or to use "1,0" and split it at load?
you are starting it backwards and as a result with end up in some strange place, code and design wise
wdym by starting it backwards?
you should not care about json or any serialization format until you make the tool that produces those levels in memory first
How would I teleport the Player to another GameObject?
then all you have to do is serializer.ToJson(level) and not care how it looks in text
get a reference to that game object and set it's transform.position to the reference's
sorry, I'm a beginner, would you mind typing the code out?
lmao all i have is class Class { List<List<List<int>>> levelData; }
start with the tool
the "timeline" should just be 1 list per bpm of the song, all songs at 100bpm
or at least as some scriptable
i dont know what that means, but you already thinking through the design it seems, which is what you should be doing
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
design it, plan it, make it, game will run levels from scriptables, then you can serialize them as any format
unrelated but 120bpm is a much more general bpm, many songs use it
[SerializeField] private Transform teleportLocation;
public void Teleport()
{
transform.position = teleportLocation;
}
This will set your position to the teleport position
set the teleportLocation var in the unity editor
thank you
ig i could also make a way for each level to have its own bpm
maybe I should forgo random movement and switch to targeted movement
oh, but that's a must!

is it a psudorandomness issue?? or is it something else
That's a smarter way of doing it. I typed it out like this. I thought the script wasn't on the player. Stupid from me.
public Vector3 positionYouWantToGo = new Vector3 (1, 1, 1) //Change the 1s to the x, y and z position you want.
void Update()
{
if (kills >= targetKills)
{
player.position = positionYouWantToGo;
kills = 0;
}
}```
idk, it might be a sort of room where all players go when they reach a certain kill score
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.
Good catch
thanks man
I didnt even read this 💀
Thanks regardless 👍
also why do you have [SerializeField] and the variable is public?
hm yeah. Would be handy to create a sort of spawnpoint-like-object. like a spawnpad on fortnite. Use the position of it + your players height in y axis.
rookie mistake I guess
you could add an offset too
or make the player spawn +2 above the object's Y axis
ye. An offset of 500 to let the players fall from the sky
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.
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
When I create a class by serializing it in editor its constructor isn't called, how to bystep it?
My eyes... For sanity reason, do not use goto but appropriate control structure.
Tile TryTargTile = null;
do {
List<Tile> AdjTiles = TileOn.GetAdjacentTiles();
Tile TryTargTile = AdjTiles[Random.Range(0, AdjTiles.Count)];
} while(TryTargTile != null && TryTargTile.IsWater)
return TryTargTile != null ? TryTargTile: TileOn;
what does the ? do? ive seen it a few times but never used it myself
Constructors use is somewhat limited because of Unity's structure and serialization. You can get around it by using the Awake function and creating settings the fields on initialization, but it can get a little more tricky depending on what you're trying to set.
it's basically a simplified way of doing an if/else.
it's a shortcut if/else
cool
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?
If you want to access json files at runtime:
- reference them directly as TextAssets https://docs.unity3d.com/ScriptReference/TextAsset.html
- put them in Resources as TextAssets and load with Resources.Load https://docs.unity3d.com/ScriptReference/Resources.Load.html
- Leave as raw JSON files in StreamingAssets https://docs.unity3d.com/Manual/StreamingAssets.html
I don't see Application.dataPath as being useful here
its the planning mods without a game case
where is the Resources folder in the editor?
or do i just create one and assume it gets correctly transferred over to the assigned path on build
read the docs for REsources/Resources.Load
i know how to do that, but if you're suggesting to remove all the tiles manually there's a chance you might miss some
yea i was hoping it wouldn't come to do that since i have scripts and colliders and rendering settings i want to save
resetting the tilemap wouldn't affect those things, no?
Anyway if you want you can just make a quick editor script to call the function in the editor
oh nvm yes you're right
i misread your answer
can someone help me with this code the gravity isnt working I keep Floating https://hatebin.com/oamoicfabf
where is your Jump function being called?
you're never calling ProcesMove or Jump
in the script below the InputManager the PlayerMotor script
ok so that makes little sense
also unity already has RigidBody component with gravity if you want to use that
you want gravity to happen all the time right?
You should be running that stuff in Update
I will try it
whats the difference of the Resources folder and the StreamingAssets folder?
read the docs for each of them. They will explain
I have.
then what part are you confused about
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
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
no, Resources doesn't work that way
so which one is preferred for holding json files
that's up to you
depends on your needs and what you're trying to do and how you want to access these files
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
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
"Object reference not set to an instance of an object" Line 20. I have the player in the scene with KillTracker attached. What do?
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
they are migrating southeast
Its bad to find by string name of the object. You should do tag instead
this is wierd
Or something else but people here tell me its bad to search by string name
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
why are your variables all class names???? dont do that
unless you setup your vars to be green
i see
huh
they always migrate in the direction first in the getAdjacency script
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 ?
you're in isometric view (no depth)
what is the point of even using Resources.Load at the point ?
im not sure.
i asked up here, but didnt get an answer
does StreamingAssets actually give me a path?
TLDR what exactly you need the paths for ? can't you just put the files inside the Local folder (Application.persitentDataPath) or whatever the custom folder you want to load them from ?
this is exceptionally odd
i just want an easy way of loading json files into a class like how JSONUtility can
the files are extremely small
okay so put your json files inside a set folder in Application.persitentDataPath (check docs where it is specific)
then do a simple System.IO lookup inside that folder and find your files that way
anything you put in there could be potentially loaded in
Are you talking about loading them in at editor time, or after the game is built?
both
Use StreamingAssets for your edit time stuff and then just designate a folder somewhere for the runtime stuff
and when i build to mobile, that folder will transfer over correctly and still be accessible the same way?
dataPath is not what you need iirc it should be persitentDataPath
oh that's whats mentioned in the StreamingAssets docs
actually wait no im reading this wrong\
Application.streamingAssetsPath is what i need
oh for streaming assets , tbh i've not used them too much
oh thats why I removed the randomness which removed the randomness from direction too
my computer does not like what I am doing to it
tfw you refactor a method to be faster but its not
for streaming assets? It's a verbatim file
if you want to use File.ReadAllText for example, that needs the full filename, yes
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?
you have constructed your ray with two positions
rays expect a position and a direction
ahhh..
if you want the direction from A to B you can get that with (B - A).normalized
e.g.
Vector3 directionToBuilding = (buildingPosition - currentPlayerPosition).normalized;```
(or drop the normalization to get a vector that takes you from A to B)
yepo
is there a better name for that
I would call that offsetToBuilding
Not sure I get the last thing, but something like that seems good enough?
this
It's kinda unclear why you are making a Ray here
since you're not using it
yes, DrawRay doesn't actually take a Ray
true true, it's to calculate the distance
the Ray type is a position and a direction
between player and building
but in your example:
Debug.DrawRay(ray.origin, ray.direction, Color.blue);```
notably, a Ray doesn't have a length
it is merely these two things
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"
public SerializableLevel GetLevel(string levelName)
{
return JsonUtility.FromJson<SerializableLevel>(Application.streamingAssetsPath + "Levels/" + levelName);
}```
looks like your json is not valid
well
actually
yeah.. weird you cant just Debug.DrawRay a Ray
you just passed the file path into FromJson
which is not right lol
you need to read the file
string json = FIle.ReadAllText(Application.streamingAssetsPath + "Levels/" + levelName);```
oh when it says string json does that mean path or file s a text
ah ok
it would explicitly tell you if it took a file path
you can do something similar, though
Debug.DrawLine(ray.origin, ray.GetPoint(length));
e.g.
does File depend on something
your IDE should tell you
but yes
btw recommend building your filepath like
string filePath = Path.Combine(Application.streamingAssetsPath, "Levels", levelName);```
Ray ray = new Ray(Vector3.zero, Vector3.right);
Vector3 start = ray.origin;
Vector3 end = Debug.ray.GetPoint(10);
Debug.DrawLine(start, end);
all it says is it doesn't exist
is this VSCode
is your IDE configured?
It should have auto suggestions
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
cool
That's pretty roundabout, of course
tyvm
what the friiiiick
whyyyyyy
using VS with syntax highlighting support so it should
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)
Those are two completely different things, yes
Target itself is null
Target is null. You get an error.
ah
because im asking if the child of the parent object that doesnt exist exists
you're trying to ring the doorbell when the entire house is missing
there is no "child" here
thats what I meant yes
sorry wasnt sure how to phrase it
Target is some unity object (presumably a MonoBehaviour). It has a property called gameObject
A monobehaviour's gameObject is never null anyway (assuming that target is MB)
gameObject will never be null on a valid MonoBehaviour
(maybe after it gets destroyed?)
hold me im scared
hopefully this is just me being stupid and not a fundamental design flaw
you will get lots of spiking in the editor
probably some mixture of garbage collection and expesnive UI updates
i dont have any UI
you mean the tint when you're in play mode?
no
the blue in the profiler is my script lag
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
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
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.
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
the issue is its procedural
hexbased
I have no idea what that distribuiton would look like, thought.
so what?
yeah
ig I could just run it once, get all of them in a collection for each tile, and then not run it again
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
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
that's better
that would be reasonable for random spread, really
So are these vectors just directions or do they need differing lengths too?
some kind of gaussian
annoyingly, there's no onUnitCircle, but I guess you can just normalize
...how did I never realize you can just normalize that to get something on the circle
you could always do onUnitSphere and then set the y?
although ig that could land inside the circle too
(but is that gonna be uniform? if the original insideUnitCircle is uniform, then it should be fine)
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)
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
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
well, two things
- you don't know what that distribution looks like yet
- 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
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
Every time you call points you are allocating and creating a brand new copy of the array from the component
and that array is not tied to the collider
easy mistake to make
you should:
- copy the array into a local variable, one time
- modify your array
- copy your array back into the component
Okay hold up wait
Vector2[] points = collider.points;
for (blah blah blah) {
blah blah
}
collider.points = points;```
okay I get it thank you I'll try
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
So it's not necessarily wrong to set one of its elements like that
I agree, this is what I am trying to do however I also need the angle too. I may just try to calculate the radius instead using this way but in respect to the angle. So hopefully that should work
Mathf.Atan2 to the rescue
although
i see
So what was doing my code before ?
you want the angle between the original vector and the new vector
Vector3.Angle will do the trick.
Danke
This would tell you the angle to the point you generated. It would be unrelated to how much you rotate the trajectory vector.
So, wrong one.
use this to figure out how much you rotated the vector
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
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 ?
accessing points was creating a new copy of the array
you were modifying one element of that array
which did nothing to do the collider
Oh so basically by accessing the points on the collider I was making a copy ?
store the array locally, modify it, and assign it to the collider's points property
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
the docs don't really make it clear, do they https://docs.unity3d.com/ScriptReference/PolygonCollider2D-points.html
there is no object
I see
Well well I get the idea, even tho I don't really know much in terminologies :3
perhaps you're thinking of the new component-based system?
where you add a NavMeshSurface to an object
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
like this?
i don't know what you've screenshotted here
this tab?
this is still part of the old system
afaik
What do I do with this? It takes me to a github page containing a project
I imagine if I wanna modify the offset of a Circle collider 2D I need to proceed the same as previously ?
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?
Perfect tutorial for what you are trying to do with tool you are trying to use: https://learn.unity.com/tutorial/navigation-mesh-introduction?uv=2021.3&projectId=5e0b794cedbc2a14eb8c900a#
I remember this in Godot, dunno about Unity
Thank you
@heady iris when you got time :3
pretty sure the offset is just a Vector3
terraria reference?
No
alright so no need to create a "copy" ?
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;
welp yeah I need to change it precisely
Exact same reason. The compiler yells at you this time, though.
xD
since it knows there's no way collider.offset.y = 0; makes any sense
good thing I haven't tried before asking
collider.offset returns a value type, so nobody else could be referencing it (by definition)
