#archived-code-general
1 messages ยท Page 261 of 1
the code here iterates each pixel in my image and writes rgba bytes to that byte array
and then gets loaded by the texture after it's done
[ScriptedImporter(1, "someExtension")], that's how importers are annotated and unity later knows which importer to use for which kind of asset
COuldn't you just use this then:
https://docs.unity3d.com/ScriptReference/Texture2D.SetPixels32.html
unrelated though is it not? still have to save that Texture2D asset to exist in the asset browser either way
btw may I ask out of curiosity why raw bytes for rgba?
you said you wrote custom parser, so this is a bit... off-putting to me (rises some flags, not sure if I used this phrase correctly)??
https://docs.unity3d.com/ScriptReference/ImageConversion.EncodeToPNG.html after importing then save the PNG?
that's what tooster recommended, it sucks they would all have to be saved to pngs as well but i assume it would work
ik it's probably against the rules here bc proprietary content n stuff but i wrote a PoC nds rom parser and im loading pixel data from textures extracted from there
for purposes other than wanting the extra texture import settings, my code works perfectly fine for pixel data n all that
Looks like you can do this:
https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
Just using a .png path and a Texture2D for the asset object
hmm maybe not actually
To my current understanding, if you want to use the TextureAssetImporter, you have to use the filetape that this importer supports
yeah if you just want a serialized .asset containing a Texture2D you use CreateAsset
and as a possible workaround, you could maybe create a derived class from TextureAssetImporter, annotate it with [ScriptedImporter(1, "yourMadeUpExtension")]
and store the asset with this made up extension
and in relevant methods call base....() if possible
ughhh TextureImporter is sealed
@rigid island
[SerializeField] private LineRenderer LineRenderer;
[FormerlySerializedAs("LayerMask")] public LayerMask PlayerMask;
private void Awake()
{
LineRenderer = GetComponent<LineRenderer>();
}
private void Update()
{
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, PlayerMask))
{
Debug.Log($"Looking at {hit.collider.gameObject.name}");
LineRenderer.SetPosition(0, transform.position);
LineRenderer.SetPosition(1, hit.point);
LineRenderer.startColor = Color.green;
LineRenderer.endColor = Color.green;
}
}
welp, then I guess going with the route of supported asset types is the best option
yeah unfortunately
I think the answer is to build a Texture2D with SetPixels32, do the EncodeToPNG on it, write the PNG file out manually, then call https://docs.unity3d.com/ScriptReference/AssetDatabase.ImportAsset.html to import it as an asset
sadly that's probably the only option ugh!!!
I don't quite understand what's so bad with that, why do you try to avoid having .png and want to keep .asset ๐
?
well bc that means for each texture i've gotta convert to png and then reimport so that doesn't end up keeping everything within unity and the code
maybe it wont be so bad tho
If you want to keep the .asset then it should work fine to create the Texture2D with SetPixels32 and then call https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
hey, why doesnt this code work ?
var content = JsonUtility.ToJson(userPost);
Debug.Log(content);
also screenshot the line currently and how it looks,, I haven't used CM pov much
the pixel loading is irrelevant to this but i appreciate the help
imma probs just suck it up and live w/o import settings
define "doesn't work"
the debug log thing just prints: {}
souinds like userPost was not a serializable type
or has no serialized members
show userPost obj
this is the class of userpost
Unity cannot serialize properties
those are all properties
it can only serialize fields
how ?
you could optionally serialize the backing fields for those properties with [field: SerializeField] on each property if you want.
e.g.
[field: SerializeField] public string userName { get; set; }```
@deft dagger
otherwise switch to fields:
public string userName;```
is there a good reason you need them to be properties? They seem to all just be autoproperties
It's the purple color, even tho I am setting it to green
im trying to get them to use them with http client
the magenta means you are not using a valid shader for this render pipeline
Irrelevant
but because it gives an empty object its returning an error that they are empty
the only thing your HTTP client sees is the serialized json
so switch to something you can actually serialize
or switch to a different serializer
so i should just delete the get set ?
that's the easiest/simplest way forward, yes.
i see
hmm maybe try just passing
var ray = cam.ViewportPointToRay(new Vector2(0.5f,0.5f));
i will try that now, thanks
keep in mind with jsonutil , if you use dictionaries you need another workaround
this would be for ViewportPointTORay
any ideas ?
oops yea you're right
if you just want ray from the center of the camera you can do this:
Ray r = new Ray(camTransform.position, camTransform.forward);```
@fossil steeple ^^ this
either selectables is nuill or selectables[_currentSelection] is null. Find out which with some log statements or the debugger
as you can see in the inspector the list has correct entries
as you can see with the debug log, its trying to get 0
i did some test with hardcoded indexs, same error
That inspector tells me that some instance of the script has correct entries at one point in time
i just edited the code by adding more list entries and now its not working (or maybe its the panel ?)
When your code is erroring, it's either on a different instance, or at a different time when there are null entries
i only have 1 instance of this mainmenu
YOu are still skipping the very first step of debugging here
figure out exactly what is null
well its the lists entries
add debug logs or attach a debugger
how do you know that?
^^ debugger is your best friend
it could be the list/array itself
because its saying its null
There are two possibilities of null things on that line
then if its null, why is it showing the correct data in the inspector at all time ?
@leaden ice
How am I gonna ignore my player this way though?
since my camera is set to look at my player all time
Rule #1 of debugging is to quiestion your assumptions
it worked ! thanks man
Already answer3ed this #archived-code-general message
I am using URP
didn't change anything really
anyway to fix this?
upgrade your material
i said i only have one instance, and the list is never changed at runtime
so i dont see why the entries becomes null
i already perfomed many checks before asking here dont worry
you are making assumptions. THe only way to know for sure is to debug
everyone goes through this. Stubbornly resisting debugging. When they finally do there's usually an "Oh! Of Course" moment and the problem is solved instantly
For erxample you're assuming the code is actually running on the instance of your script in your scene
maybe it's running on a prefab, for example
for example; i made a foreach, its printing all objects, but throws an error for one of them
Debug.Log(_selectables.Count);
foreach (var selectable in _selectables)
{
Debug.Log(selectable.gameObject.name);
}
i am not stubbornly not debugging, i already debugged and not finding the issue
Very clear from this screenshot that you have two copies of the script
ignore the player layer , also if you use the third person mode in cinemachine you can offset the shoulder area
you are right, apparently i misslicked by applying a prefab changed to the parent
im sorry if i appeared rude, ty for helping out
as Sherlock once said:
When you have eliminated all which is impossible, then whatever remains, however improbable, must be the truth
one of the most difficult tasks in software development is to not make assumptions and know. it's like looking at a line of code and seeing what is actually there rather than what you think is there. The mind plays tricks on you

It's useful to start with assumptions, but to then quickly relax them
I don't immediately check "does this object even exist?" if a new piece of behavior doesn't work, since I know it does probably exist.
But you need to be able and willing to start challenging those assumptions.
you guys are lucky, imagine us poor bastards before the days of ide's and debuggers when all we had to go on was a screen full of hex
yeah i usually check all my code, even if i dont see why there should be an issue
but here it wasnt a code issue but an wrong human movement
but it caused a code issue, one of the reasons I always debug the instance id of the object so you can instantly see if it's the object you think it is
how can you debug the instance id ?
make debugger your best friend
Debug.Log(GetInstanceId());
every unity object has an instance ID on it
that great, didnt know it existed
also useful info, prefabs have positive id's scene gameobjects have negative id's, so it's easy to see if you are referencing a prefab by accident
Smells like some decompiling business. Unity compiles code automatically for you, you dont need to do anything yourself. Sounds suspicious that you have "source code" yet dont know how to compile it
Is this some publicly available code you just downloaded? How was it shared? I assume this was given via github, so the project should be playable as soon as you open it in unity.
Ask about the specific errors in that community you mentioned. Fixing them yourself might require you to learn some basic coding. Modding/decompiling talk isnt really allowed here or I'd offer to help further.
The errors could even just be nothing, unless you cannot run the project at all because of it. It could even just be an error because of a unity version difference
I have no clue what to do. Ill just get rid of my messages not to clog the server and go on my day. I would happy to learn unity and stuff but alot of stuff is going on in my life now.
Best bet is what I said in my previous message, show the community that you mentioned the exact errors. They likely know how to fix it
Hey, I've got a question for those a bit more experienced , I'm relatively new to Unity after switching from Gamemaker and so far have a pretty decent setup for my current project where I'm working on a saving/loading function and I use a tilemap for building structures and want to save the full tilemap and convert it to a string so it can be saved correctly which I have managed to setup, the only issue I have right now is it seems like the game is only saving a certain section of the tilemap and ignoring the rest as when I load the save I can only see tiles I placed in that particular area. As far as I am aware the save function is checking every possible tile that can be built on so it is confusing to know what i'm missing here. I consulted ChatGPT which suggested checking the tilemap bounds are set correctly which I am not sure where to check this in the editor either, Any help on how to check tilemap bounds or another method to try saving the tilemap would be great , Thanks
Would anyone know any reasons as to why omisharp is not starting in vscode (no omnisharp logs)? I had intellisense yesterday, but opening the project today its not working. I have the latest mono version, dotnet 6, and omnisharp.UseModernNet set to false
Also for some reason, everytime I come back to Unity, there's always something that goes wrong with intellisense in vscode
Start from sharing the relevant code.
Did you check the saved string for wether it contains the missing tiles data?
Question on Pac-Man Clone Based on Guide Playlist
you're using old method which is outdated
yeah thats because VSCode isnt officially supported by unity
flawless experience would be Visual Studio
or Rider I suppose if you can afford it / are student
anyway the new method for vscode is outlined here below โฌ๏ธ
!vscode
weird way to say it's supported but the extension has changed and is now developed by microsoft ๐
yeah it was only dropped for a bit till ms picked it up themselfs
though i am partial to team
here
yeah Microsoft but Unity for some reason doesn't care to support it even though they use it themselves lol
why spend the resources is MS alreayd is
Microsoft made smart move for market share
the Rider one is also included in the package manager too but is all maintained by jetbrains
Devkit after all is a licensed product like VS
I can't seem to get this script to work, it has 2 errors, that the problem, is that its suppose to be a 2D sprite adventuring around a 3d climate, follow camera, able to rotate around like a computer mouse.
those are warnings , its saying your current animator controller doesn't have those parameters
do you know how to solve the problem?
https://docs.unity3d.com/Manual/AnimationParameters.html
Add the parameters
that part is what I have of parameters
are you sure this is the controller you are using on the Animator component ?
that's what I have set
can you show the inspector for that
thats not the animator component
its the inspector for a blend tree
they seem different
and yea thats the one
character_animator1 vs player.controller
SpriteDirectional is the script thats causing those warnings?
Yes.
can you show script
Hi, I am trying to build web3 game by using Unity, does anyone know which web3 SDK is better to start with? thirdweb or safeChain? Thanks.
nah send with link !code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yup just checking if maybe you had start method that was doing GetComponent
ok
you do have the wrong controller on player
what is the right controller for player?
the one called Player
and set it to the sprite directional controller?
no not sure where you even have this Animator at, use the one already on player and replace the one there
Idk i guess this doesn't tell me anything
oh
kinda irrelevant to your fix though lol
ok where do we continue?
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
this script is so rare though
this has 0 to do with scripts
the fix here is to replace your controller character_animator1 to Player one
in the Animator referenced by the SpriteDirectionalController
that it?
how can I tell if you cropped the whole image..
by the text of it
the text is irrelevant if its the one on the wrong object
ok, clear the console first and then run the game see if its gone
he doesn't move though
as if the script and setup/settings is not complete
I just installed Unity on this pc
I lost all my scripts
sounds like you should learn how to use Version Control
yeah its easier to get started with an interface in the beginning, Github Desktop is a good app
as for code i would suggest you get into some sort of course the unity ones I linked are free
i did quite a few amount of times on that unity learn option
stuck on graphics
ill eventually continue that
wdym by Graphics
the third portion
"Creative Core"
I also have Udemy.
is it possible to get this guy moving tonight?
if you're committed to debugging
debugging I am committed to doing
I assume that the player controller doesn't have keys setup
the input of " w a s d"
I thought you had an issue with the animation? What do the controls have to do with it?
the animation is created, but the keys don't seem to do anything when I press them
Maybe start from explaining the issue in details before moving on to debugging. Share a video of it if words are not enough.
you have none of that in this code
ok lets get the code adjusted then?
where would that be?
you have to code stuff in its not magically there
i remember setting up a controller, but it took some time
isnt there a package of it?
there is a built in Input class
there is also a newer Input System unity released as package
whats the name of that?
the name of what ? Input System, I just said it lol
ohh
The input system is not gonna add character controller logic for you. You have to code that.
I wouldn't worry about that now, learn the "traditional" way first
Start by going through unity learn or looking up a tutorial for a character controller that suits your need.
ok brb
Is there a way to check the storage space of a hard drive for android, Can't seem to find any form of documentation especially since I am planning to use addressables or similar for external download
there is always a way, you have too choose if you want to code that in or use a plugin
code it in if it just something simple and basic as in get how much free space left. oh.
does unity have that built in?
you're in a code general channel, that should be expected..everything is done in code
in internal api no
something like this maybe ?
https://github.com/dkrprasetya/simple-disk-utils
strange, unity have addressable but don't have a system that checks for storage
uinty also has code to open file/directory dialog for editor only, but not for the build.
gotta take what you can ๐คทโโ๏ธ
my friend has a main menu where after he presses the button and goes to his main scene, the lighting in his scene is messed up
also that happens because light wasnt generated so light data is missing
is [SerializeField] somewhat new? I am seeing most tutorials just use public for things that should be serialize field
Does anyone know how to set this lesson to work?
Hey everyone! Welcome to another tutorial!
Unity version in this video: 2021.3.5f1
Sprite Billboard Video 1: https://youtu.be/FjJJ_I9zqJo
Time Stamps:
0:00 - Intro
1:11 - Late Update
1:34 - Sprites & Imports
3:22 - Animations
6:20 - Sprite Directional Controller Script
11:50 - It's (sort of) working!
13:17 - Now it's working!
โฎ ๐โโ๏ธ Social ...
Hi, i've found a script from an old folder in my pc, what it does is actually extract out the trees painted on the terrain as the original prefab in the world space (detached from the terrain) , but the problem is , all the painted trees grab the scale of their root prefabs , and the size variation of them when being painted on the terrain is lost, my question is, is it possible to keep their random scale retained even after they are extracted out from the terrain? (long words sorry)
here is the part of the code below
TreeInstance seem to have a widthScale and heightScale properties which are supposed to correspond to it's scale.
remove instance(j)?
everything works okay, it was supposed to extract out the painted trees from the terrain to world space and copy the root prefabs world scale ...i mean , all the bamboo trees are extracted out from the terrain , and they are now individual game objects, ...here i just want to make a little change, i want the trees have their scales(height , width) unchanged like they were painted on the terrain with random height ...instead of the inheriting the scale of the root prefab, because , when they get detached or extracted from the terrain , all trees have same heights , which is against the true nature ..haha
ok i finally got a basic scripting system working
I added an Xbox controller to it, but doesn't work to operate a sprite to me yet.
Well, your code should already be doing that.
it somehow doesnt ๐
those little kids are the extracted ones
How are they supposed to look? And is the prefab scaled as 1 1 1 by default?
sorry , i have notice another thing , it doesnt even inherit the scale of their root prefab
just a constant number 1.09 or something on x,y,z scale
Because the width and height scale are relative to the original prefab scale, not absolute. You'd need to multiply it by existing scale if you want to keep the prefab scale.
But ideally you want your prefab unscaled.
yeah, i just want to leave the trees scale as is painted like on the terrain
im not good at coding, could you just guide me where to modify?
You'd need to learn it then. It's not that hard. You just need to multiply the scale from the terrain data with the prefab scale.
If you're having trouble with coding I suggest to step back and do proper learning before continuing.
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you
are you not tired ? you've been providing this message lots of time. anyway you cute bot
anyone know how to list files in firebase storage?
Hey guys I'd like some help with a problem that's been driving me nuts
I'm trying to get an orbital rotation working but I have a problem when I move from one 'planet' to another.
This simple function works when I start with the correct orientation inside the gravity of my object, which is recognized by a trigger collider.
private void RotateAroundObject()
{
player.transform.RotateAround(transform.position, direction * player.transform.forward, orbitSpeed * Time.deltaTime);
}
I'm trying to fix my weird behavior by aligning the box collider of my object and the circlecollider of my planet
If anyone has any advice on how to implement this I'd be most grateful
can you explain the issue more beyond it just not working
current behavior is the rotation is fixed around the point of contact between the two colliders.
My idea of how to fix it is by having the center of my box collider travel along the edge of the circle collider.
I will then need to ensure that the rotation is correct and add some logic to have the rocket spin correctly depending on the orientation it approaches from
why dont you just use a spin function using mathematics instead of relying on circle collider
the collider acts as the trigger for the rocket to begin orbiting a planet
public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 axis, float angle)
{
Quaternion rotation = Quaternion.AngleAxis(angle, axis);
return rotation * (point - pivot) + pivot;
}
This is my rotatearound method I've made which behaves similar if you can figure out your logic from that
there's a reason I use this over rotate around but I forget
oh, right. It's not tied to transform
already doesn't like it in 2d :/
Ah, can do all operations in 3D then just return as 2D. I think that should still work
it's just an alternative though from rotatearound but it's basically similar logic if you wanted to know how it worked
I tried it as is with
player.transform.position = RotatePointAroundPoint(player.transform.position, transform.position, Vector2.right, orbitSpeed);
and my rocket is stationary
did I misunderstand any of the args?
why arent we using the standard matrix multiplication to orbit the object
I'm not familiar with this
yeah that fixed it, but then it introduces the issue of having to adjust my rotation every frame
Because it's not needed, matrix is a lot more values and we have built in quaternion functions that do most of what's needed already
Matrix multiplication alone means nothing here though, i assume you mean transformation matrix
I mean, if you're trying to emulate the gravity pull and rotation, I'm not too sure this method (or rotatearound for that matter) is the idea, but if you want consistent rotation around the object then this works.
nah not that granular, just a simply circular orbit is fine
the concept here is to jump from planet to planet and be able to orbit each one
I use it to spin fireballs around me because applying velocity with rotation values eventually build up rotational drift (floating point problem) so just calculating the point every update keeps it accurate
also, as I'm reading into it, lookrotation seems to be a function in 3 dimensions, and I guess getting an orthogonal vector in 2D also gives me a 3D vector
but it's been a long time since math and physics so ๐คทโโ๏ธ lol
you could make 2 AddForce to the orbiting objects. One towards the Current Object Position projected onto the orbiting line. and one is your already orbiting direction
Not really sure what you mean by that, but you do not magically get a 3d vector from 2 orthogonal vectors
Orthogonal just means dot product is 0
2 orthogonal 2d vectors would just span the 2d space
all of my rigidbody is kinematic so I have to configure my own physics system
kinda annoying but more choices
I X J = K, no?
z still kinda exists in 2D as I guess you can see that we're rotating on it. You're still like looking at it if it were being moved around on a table, so there's still that axis of depth and even if you don't move on it, it's still relevant
technically 4D if we're using quaternions but I've no freaking clue how they work
I'm not really sure what you're referring to by this but regardless you dont really need to know much true linear alg for unity.
okay my bad, I'm probably all over the place as I'm trying to learn how to incorporate these concepts
Either you are referring to some advanced graduate level concept beyond my knowledge, or have a big misunderstanding ๐
it's definately the latter lol
back to the problem at hand, what should I do to keep my rotation consistent with my position as I orbit?
RotateAround kinda did both for me, and I mean it worked fine until my rocket hit the trigger of a different planet
What happened when it hit a different planet?
then check inside of it
there we go
this with rotatearound? Doesn't seem to keep the direction either
yeah this is with rotatearound
in that case you'd have to calculate the direction each update if you want to facing to be accurate
but if you want to do it the easy way, just get a direction from the last position ;)
๐ค
but otherwise the object's rotation doesn't matter
what do you mean?
rotatearound just lerps a position around a point without any regards for the rotation
like, you're not applying forward velocity anywhere here
oh, yeah.
I only apply a force to apply thrust, and I turn off my collider for a second so it doesn't interfere with my trajectory while in bounds
otherwise it's simply rotatearound the whole time
that's probably your fix anyway so try that
I just need the rocket to orient properly when it hits a second planet and I can breathe again
hmm so if distance < radius - someValue then start spinning?
yeah, and then you can probably just define the orbit radius per planet
cool, I'll give it a shot
you want to check it inside of the trigger, so that should always be further than the radius
another idea is to use MoveTowards
with conjunction so it always moves to the radius
incase you overshoot
yeah my first idea was to move the center of my box collider ride the edge of the circle collider but I couldn't figure out how to calculate the closest point on the edge of the circle every frame.
well, it does two things, moves you towards the planet or moves you away if you want that
I use it a bit to make some spiral effects with my rotational methods
both methods are just lerping methods with a little more logic
welp 1st attempt didn't work
void FixedUpdate()
{
if (pcG.orbitingBody != null && pcG.orbitingBody == gameObject && inRotateDistance())
{
RotateAroundObject();
}
}
private bool inRotateDistance(){
return player.transform.position.magnitude - orbitDistance > Vector2.Distance(player.transform.position, transform.position);
}
man I'm bad at this ๐
just orbit distance
orbitDistance >= Vector3.Distance (if orbit distance is greater, then we are in orbit and should rotate)
I think? Too sleepy but just comparing scalar values
anyway gtg, if you're continuing to have troubles, be sure you're logging your stuff
Thanks Mao
Hey, is there a built in method that can resize rect transform width with automatic position change so the rect won't move? Same as when we drag for example right size of a resize tool in rect transform
I tried this but doesn't work for me sadly. I can pass only horizontal axis, i need something specifically for right side drag
then you have probably anchored your rect transform incorrectly
True, i had my x pivot on 0.5 ๐คฆโโ๏ธ
Thank you very much ๐
Hey, so 2 players start running at the same time but the window that is active (Clicked on) that player will move faster and further then the other player.
Set editor and parallel sync to focused.
Also added run in background
Still not working any fix?
my code messiness is scaling very quickly ๐ฅ
nice
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PotObjectAction : ObjectActionBase
{
private float waterLevel = 0;
private GameObject mesh;
void Start()
{
mesh = transform.Find("water").gameObject;
SetWaterLevel(waterLevel);
}
void FixedUpdate()
{
print(waterLevel);
Vector3 cameraPos = Camera.main.transform.position;
float distance = Vector3.Distance(cameraPos, transform.position);
if (distance > 50) return;
Vector3 up = transform.up;
if (up.y < 0.5f)
{
waterLevel = Mathf.Max(0, waterLevel - 0.0005f);
SetWaterLevel(waterLevel);
}
}
public void SetWaterLevel(float level)
{
// -0.019 - 0.336
float diff = Mathf.Abs(-0.019f - 0.336f);
mesh.transform.localPosition = new Vector3(0, -0.019f + (diff * level), 0);
mesh.SetActive(level > 0);
}
public override void OnWatering()
{
waterLevel = Mathf.Min(1, waterLevel + 0.005f);
SetWaterLevel(waterLevel);
}
}
hey, I got this script, and on fixedupdate it prints two values (like 0.5, 0) and I have no idea how, there is only one pot, only one script
it breaks my script beacuse here
if (up.y < 0.5f)
{
waterLevel = Mathf.Max(0, waterLevel - 0.0005f);
SetWaterLevel(waterLevel);
}```
it sets waterLevel to 0
instead of
print(waterLevel);
use
Debug.Log($"{GetInstanceId()} {waterLevel}");
this will show if there are 2 objects
How often do you guys set component references in the inspector as opposed to using GetComponent in Awake/Start?
when ever possible
Same pretty much. Which kinda makes using interfaces rough imo.
Apart from pooling a bunch of squares and placing them as a grid, is there a better way to create a 2d grid with selectable tiles in your opinion?
one way would be to just do calculations on a 2d texture and change the colors based on mouse position
there is a grid component you can use with tilemap
you can also just use it on its own if you want as well, so you can take a world position and convert it to a tile position for example
tile pallette only works in Unity editor
i just went with pooled cells
actually need them as separate objects
On the other hand i dont know how performance heavy is having 2k+ square objects in a scene
you should be fine
if it becomes a problem there are other approaches like generating a mesh to repersent it all as 1 object
as far as selecting them, it would be cheaper to just do the math to convert from a mouse to world coord then to a grid coord then using raycasts and colliders
i did selecting with just basic math, but came up with a better solution, just generated a huge square based on the size of the grid, and then change the position of select square based on the pos in grid.
Im getting an error trying to save a file: UnauthorizedAccessException: Access denied
File.WriteAllText(Application.dataPath, json);
How do i fix this?
and for keeping track of the cells i have a list of cell objects
is this android?
regular windows
why are you writing it to the project folder and not the persistendDataPath
Really no runtime code should ever need to hit the dataPath
You mean this?
File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), json);
same error
well give it a filename
"C:/Users/Uporabnik/AppData/LocalLow/DefaultCompany/Potapljanje" that is a file name tho, i just checked it exists
thats not a filename
thats a folder of your project appdata
oh im stupid
you need to join it with something else to get a file name
Path.Combine(Application.persistentDataPath, filename)
yep, i followed a tutorial and missed the main part, sorry, thanks tho
What variable type can I use to read such a json into a unity class?
I cant use Vector2[], float[][] or List<List<float>>
does anyone know how to read it. And yes the Arrays with the numbers are always 2 in length
"test":[
[
12,
14
],
[
52,
57
],
[
17,
28
],
[
25,
72
],
[
83,
23
]
]
pretty sure both float[][] and List<List<float>> will work
though do you want float or int, since the data has no decimals?
yea i want float. in the real json its only floats
or make it a custom class/struct no? then a list of it
past that you could do some custom deserilize logic for a custom struct
but without custom logic would need a list of list of float or a 2d array
Unity's serializer doesn't support directly nested arrays/lists. You have to wrap it in a serializable class/struct.
public class TestItem
{
public int thing1 { get; set; }
public int thing2 { get; set; }
}
var result = JsonConvert.DeserializeObject<Dictionary<string, List<TestItem>>>(json);
if (result.TryGetValue("test", out List<TestItem> testList))
{
foreach (var testItem in testList)
{
Debug.Log($"Item1: {testItem.thing1}, Item2: {testItem.thing1}");
}
}```
maybe
which i heavily recommend to use over JsonUtility, its a more more complete implementation of json with way less gotchas
this is my code
public GeoJson data;
[System.Serializable]
public class GeoJson
{
public string type;
public Feature[] features;
[System.Serializable]
public class Feature
{
public string type;
public Geometry geometry;
[System.Serializable]
public class Geometry
{
public string type;
public float[][] coordinates; // here
}
}
}
public void LoadJSON()
{
string json = File.ReadAllText(path);
data = JsonUtility.FromJson<GeoJson>(json);
//Error object reference not found
print(data.features[0].geometry.coordinates[0]);
}
dont think that would work
Ahh ok just doing a quick thing , haven't caffeinated yet so prob is wrong ๐
since the inner items also use [] so are not structs
ahh i see
though with json.net you can setup custom logic for how to treat certain types, so you can really bring it into what ever you want if willing to do the extra work
ok thanks for your help I will try that
yeah, which is extremely useful
I have a bunch of "Identifiable" scriptable objects that all have GUIDs stored in them
if the List<List<float>> does not work, its because of a limitation in JsonUtility
I have a converter that serializes them as the GUID and deserializes them by looking the GUID up in a dictionary
yum, GUIDs for breakfast
(maybe these should be base64'd)
yeah have done it to just make some simple struct types more condensed too, like something that repersents a range just ends up as "min:max" in json instead of a object
or maybe I'll just go straight to a binary format. who knows
depends on what its for, i have done a lot of binary formats in the past
they can be very useful when you dont always need to read the whole file
im not that experienced. I have no idea what you guys are talking about haha
basically, JsonUtility can only turn some things into JSON, and you can't really customize how it does that
Json.NET (a third party library) can serialize more kinds of things and gives you many more options
It's also just about as easy to work with.
var data = JsonConvert.SerializeObject(obj, Formatting.None, settings);
File.WriteAllText(path, data);
ok ill see what i can do but thanks again
JsonUtility is ok for basic stuff but its total crap for everything else
Json.net is soo good unity added the package to its PM
https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html
if using it i would also get
https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters
works on my machine
more or less just provides special converters for a bunch of the unity types to reduce what is written to only what is required and kill a few recursive problems
like vector3 containing other vector3's etc
also adds some other nice converters you can toggle on and off, like one that understands the version type, or have the StringEnumConverter on by default
or DateTime as either unix epoch or iso
somebody help me?
the object not accompanies the character's hand
Not a code question but you should parent it to the hand bone not the hand mesh
I have an issue where the part of the code that is supposed to add a control state flag in the "if" statement does nothing.
Removing a state in the "else" works flawlessly, so idk what could be the issue.
[Flags]public enum PlayerControlsState
{
None = 0,
Movement = 1,
Others = 2
};
public delegate void ChangePlayerControlsState(PlayerControlsState state, bool toggleOn = true);
public static event ChangePlayerControlsState OnPlayerControlsStateChanged;
public static void RaisePlayerControlsStateChanged(PlayerControlsState state, bool toggleOn = true)
{
if(toggleOn)
{
UserInput.Instance.CurrentControlsState |= state;
}
else
{
UserInput.Instance.CurrentControlsState &= ~state;
}
OnPlayerControlsStateChanged.Invoke(state, toggleOn);
}```
[Flags]public enum PlayerControlsState
{
None = 0,
Movement = 1,
Others = 2
};```
This is not right for a flags enum. You need:
```cs
[Flags]public enum PlayerControlsState
{
None = 0,
Movement = 1 << 0,
Others = 1 << 1
};```
although technically those are the same
haha
so maybe that's not the issue
if you have 3 as a third flag value that would be wrong
yea, I did try the other one b4, and sadly I have the same issue
What debugging steps have you taken so far?
this is an issue with an unsigned value type which you're not using
I did take a second look just to be 100% sure I didn't miss a thing ... and of course I messed up the order of operations in a diff spot and now everything works
Thank you
Hello, I'm storing all raycast targets in the list. Is there any way to catch targets without Raycast target being true ?
PointerEventData eventData = new(EventSystem.current)
{
position = Input.mousePosition
};
List<RaycastResult> results = new();
EventSystem.current.RaycastAll(eventData, results);
wouldn't that defeat the whole point of Raycast target?
it would
I just wanna find Images even with Raycast target set to false
images from where and why does raycast target need to be off?
nope - they are excluded from raycasts
What are you trying to accomplish?
hello, i'm trying to save data in a file for my game using application.persistentdata, but it keeps telling me that there is no authorisation, how do i fix this
you probably have a bad path
e.g. you did
Application.persistentDataPath + "save.json"
if there's no trailing slash on the path, then you'll get something like
.../CompanyName/ProductNamesave.json
You should use System.IO.Path https://learn.microsoft.com/en-us/dotnet/api/system.io.path?view=net-8.0 -- specifically, the Join method https://learn.microsoft.com/en-us/dotnet/api/system.io.path.join?view=net-8.0 -- to combine path parts together
ive implemented this and its still not working
wdym by "it keeps telling me that there is no authorisation"?
Show your code and show the full actual error message
heres my code where path is application.datapersistent and filename is data.game
thats the error
Where did you get path from?
That is not Application.persistentDataPath
that path doesn't look like Application.persistentDataPath at all
That looks like possibly Application.dataPath
that doesn't show us where path comes from at all
show the constructor for FileDataHandler
why such a complicated setup for just reading a file
you can just use File.ReadAllText, yeah
I used to use exactly that setup until I realized there's a simpler way
its json, so you need all the data at he same time, so might as well just use the simpler command fen mentioned above
the streams are mostly useful for cases where you dont want to read the whole file at once, but since its json you can not take advtange of that
oh okay thank you
could be reduced to just the File.ReadAllText followed by the FromJson
I'm still confused by your persistent data path, though
It's supposed to point into AppData
whats it pointing to?
a folder in the user directory that ain't AppData
that looks like its dataPath
it's like it neatly skipped over AppData/LocalLow/
Perhaps there are multiple things creating FileDataHandlers or something
or the code hasn't been saved
would assume that
so unity is running something old
i dont think my unity is fully updated should i update it and also check where the project is saved?
this has worked the same for literally every unity version
log Application.dataPath and Application.persistentDataPath as a sanity check
would just make sure you are infact running the new code
okay ill do that
Okay, it's not trying to open a file in AppData
You must have had Application.dataPath previously
okay, what do i need to do?
I'd go look in that directory -- AppData/LocalLow/... -- and see if data.game is a folder
You might've accidentally created one at some point
That would cause an "access denied" error when trying to read it, iirc
If you can't find it, you can open the Run dialog and enter this
%AppData%
This will take you to AppData/Roaming, so just go up one level
then go down into LocalLow
And if in your previous code, at some point you did not use a using statement, and an exception was thrown before the stream could be closed, then Unity might have kept a dangling file handle to it. Restarting Unity might fix it.
Ah, good point
for this case would restart unity and use File.ReadAllText in the future
but if you do need to open file streams in the future i would always put it in a try/finally
using cleanly handles that for you (:
so the finally clause can close things, or let using dispose it
does using still work on exceptions?
cool
You can use both a using statement and a using declaration
It compiles to a try-finally
I use the statement form for IMGUI
using (var _ = new GUILayout.AreaScope(new Rect(10, 10, 300, 300)))
{
// IMGUI in here
}
though all of this requires disposers, what i really like was Go's defer statement lets you queue up any function including a closure to execute on exiting method scope, but before return
defer is magic and so much more flexible/useful than try/catch
@leaden ice familar with Go, or a other langauge that uses defers
I use Go professionally
nice, its amung my favourite languages to work in at the moment
I have implemented the logic for stretching and dragging panels. The stretching shouldn't work if there's a UI Object over the Object with those scripts. That's why I am checking whether the "stretchable" or "draggable" object equals to the first raycast target object. If not, stretching or dragging won't be able
Oh, and now I have a question for myself. Why would I even need to find those objects without raycast target?
do all your dragging etc with the event system and you get this behavior for free
you're writing a lot of code to basically recreate the event system's default behavior
It has built in drag/drop support
No, it's not gonna work out
you're right, it doesn't work with stretching threshold though
stretching threshold means that stretching may start in the selected range from panels' borders
So you're saying event system won't work because you want to be able to start the drag from outside the border?
Yes, I suppose so
you can manually raycast from the event system
so cursor is gonna be activated and it doesn't care wether there are some other objects nearer to the camera
Sorry, what do you mean?
so you could start it based on what ever input you want to start the drag, and just manually cast looking for hits
stretching?
I have implemented that already, so that's no problem
i've spent a while looking for appdata\locallow and i can't find it is it supposed to be there?
where are you looking?
LocalLow is inside of the AppData folder.
I showed you how to open AppData/Roaming
I think AppData is hidden by default
so you wouldn't see in your user directory
it shows you the exact path, just like log Application.persistentDataPath and copy that into a file browser
that too
So my question was redundant from the start, because I haven't mentioned it was already solved even before I asked it.
I created a TargetBlock script for objects with Raycast Target checked. If TargetBlock.block is false, the object shouldn't block my StretchablePanel even with having Raycast Target checked.
i often end up making a some menu items like this
public static class PersistentDataMenu {
[MenuItem("Persistent Data/Clear Persistent Data Path")]
public static void ClearPersistentDataPath() {
var directory = new DirectoryInfo(Application.persistentDataPath);
foreach (FileInfo file in directory.GetFiles()) {
file.Delete();
}
foreach (var dir in directory.GetDirectories()) {
dir.Delete(true);
}
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
}
[MenuItem("Persistent Data/Reveal Persistent Data Path")]
public static void RevealPersistentDataPath() {
EditorUtility.RevealInFinder(Application.persistentDataPath);
}
}
so i can quickly go to the persistentDataPath and clear it as needed
I haven't mentioned that, because I thought I should've used it for objects without Raycast Target
yeah i found it i was just being dumb sorry theres no data.game file there
so you have not executed the code to create it yet, since fixing the path
your code checks if File.Exists returns true, so it's gotta be seeing something
yes, obviously
so there is a folder, isn't there?
wdym
I mean exactly what I wrote. There's a folder named data.game in AppData/LocalLow/DefaultCompany/Shooter Game/, isn't there?
yes there is
hence why I asked for this
don't create a directory with fullPath.
string dir = Path.GetDirectoryName(fullPath);
Directory.CreateDirectory(dir);
File.WriteAllText(fullPath, jsonString);
It's ok to do this unconditionally
it will do the right thing
you can use Directory.Exists if you really want to
but yes, it's fine if you create a directory that's already there
tbh, the complete code is nonesense
the rest can be completely replaced with File.WriteAllText
the overall logic is...wrong, though, yes
you're checking if a save file already exists
if it does, you create a directory
if it doesn't, you try to write a save file
but since you created a directory at fullPath, File.Exists will always return false and you'll just try to create a directory again
this is all you need.
static void Serialize<T>(T obj, string path, bool onlyCreate)
{
var directory = Path.GetDirectoryName(path);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
if (onlyCreate && File.Exists(path))
return;
var data = JsonConvert.SerializeObject(obj, Formatting.None, settings);
File.WriteAllText(path, data);
}
here's my Serialize function I use for everything
I actually just updated that code this morning, hah
You can remove the if check here too:
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);```
yep
just didn't actually change it
I use onlyCreate to generate a settings file on first launch
then you could have the decency to give it a false default value, lol
this method is private; you call public Serialize and SerializeIfMissing methods.
they have a params argument, so no default arg for me
i build the path out of one or more strings
I did flip-flop on that several times, though (:
is this still wrong?
this is still very wrong, yes
oh god
you're checking if a file exists
pay attention to what you're doing
you don't need to check anything at all. just use Directory.CreateDirectory(dir); to ensure that all of the directories on the path exist
The rest looks reasonable enough. You will want a way to indicate to the player that saving failed, though.
he said PAY ATTENTION
im trying
look at the file you are trying to write
you can't just use random variables
each one has a very specific meaning
dir is the directories leading up to where you're trying to write this file
please im only in school this is for my coursework i started learning c# a couple months ago, what do i need to do instead here
this problem has very little to do with C#
and mostly to do with...reading. look at what you are doing
explain to yourself exactly what each line does and why you couldn't change it to other variables or other functions
i really don't know where the error is i'm sorry im really struggling to see what i'm doing that's wrong
There are only five meaningful lines of code in that function.
ask yourself which variable contains the directory and file name you want to write
Don't just stare at it.
I'm not joking. Explain what each line does out loud.
its just about attention to detail, regardless of if you stick with programming or not, its a good skill to have
prove to yourself that every variable and every function call makes sense
think about what each line does, and what each variable repersents
Hello, has anyone here worked with a graphql database by any chance?
yes, it's absolutley terrible
at this point anything is better than what i am going through right now trust
i seem to get html back for some reason from my requests
should return json or xml
it should return json
then the end points have not been configured correctly
they are as i have the same project on react and it works fine, i can also see it on the playground it works fine
that makes no sense, end points do not respond differently depending on the user agent
i know right
yh i am unfortunately very aware of that
what do you mean by this?
look very carefully at how you have composed your query, one simple mistake can invalidate the whole query, the joys of json formatting
again its correct i can see it in the playground
but really this is outside of the scope of a Unity server
Maybe you're not passing the correct Accept header? Or no header at all
well i am only having problems on unity thats why i came here but i do understand that
make a console program using HTTP Client that works, then implement the same thing in Unity
just so we are clear are you asking me to make another program outside of unity that basically fetches this data?
and then try to rewrite the code used for that in unity?
what I am saying is take Unity out of the equation. Make something that works first, then transfer that to Unity
i have used either
www.SetRequestHeader("Content-Type", "application/json");
or
www.SetRequestHeader("Accept", "application/json")
exactly, I said use Http Client
i do have something that works i have a react project that fully works, we need to transfer everything to unity
but react is not C#
i know that but surely that shouldnt really matter as its just a request right?
If you get HTML from the endpoint then save it to a file, and read it. It might contain essential information
Inspect the HTTP return code as well
almost definitely the html is an explanation of the http error code, probably 403, 404 or 500
returns 200 so i know it works
nah
i don't know where can i ask this
but i want to know why i've created an Multiple Sprite
of 32x32
and Unity imports the sprite bad
turn off filtering and compression
Oh thanks
also not a code question #๐ปโunity-talk
is just that
one sec
Sorry
i didn't know
thanks
u good np ๐
ok anyway i will see what i can find in the most remote repos just sort of glad to know its hard to work with in general makes me feel a bit less stupid
is that supposed to be a valid query?
yh
Post the HTML/XML you get when querying from Unity
Alternatively you can open your browser's dev tools and inspect network traffic there
its a lot of code its literally all html css so will just post this
as this is a code channel you could actually just share the code you are using
fair enough give me a sec
Not enough info, the useful stuff will be in the body, after the style. Save to a file and post it here !code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that is not the graphql rest api
Yeah that's your playground most likely lol
Seeing the <title> element
The playground itself will request an endpoint for you, when you hit "Send" or whatever, your code needs to hit that too
You get an HTTP 200 because the request is technically successfull, it loads the playground front-end page you showed above
ok so this is the "HTML and CSS" https://gdl.space/lebuxufivo.xml
and this is for the func i am using
https://gdl.space/lukunukule.cs
Yes your HTML seems like it's the source of this page ^
It's not how it works
The GraphQL server (?) exposes an API endpoint and a playground for convenience - you need to request the API, not the playground
your query is totally misformed
is it ok if i share quick screenshots of code or is that against the rules?
sure
I see your code, it's the value of graphqlEndpoint that's incorrect
this is on the react end this works fine
this is an example of a correct graphql query issued via c# httpclient
string qry = @"{ ""query"": ""{ Student (id:"+pid+
@") { id registrationForm { displayShortName } firstName lastName firstEntryDate leavingDate curriculumGrade { code } " +
((askForSiblings) ? @" siblings { id } " : " ") +
@" eligibilityRecords { displayName startDate endDate } postalAddresses { displayName } " +
@" mealChoices { appliesMonday appliesTuesday appliesWednesday appliesThursday appliesFriday appliesSaturday appliesSunday " +
@" mealProvision { displayName isSchoolHotMeal isSchoolLightMeal isSchoolPackedMeal isStudentPackedMeal } } " +
@" } } "" } ";
there is a big difference with react
If the query was incorrect it would have not returned HTTP 200
it did not see the query
My guess is that the URL is not the API endpoint one, and it happily discards the body when you access it
Fix the URL, then once you start getting HTTP 400s, fix the query
agreed
ok i will see what i can do, thanks anyway for the time it was appreciated
unfortunately I cannot share more code with you because it is covered by NDA, but if you still have problems tag me
https://gdl.space/kibimapizi.cpp hi how would i slow down the coroutine or prevent it from doing my whole array all at once, since it goes straight to wave 5, i used a boolean but it doesnt delay it at all
Well, you're waiting for 0 seconds, so what do you expect?๐คทโโ๏ธ
even when i wait for longer it doesnt change much
also when i make it longer, it goes straight to wave 5 and skips the first entirely
You're also starting the coroutine in update. It's likely that you have several instances running.
Do proper debugging to see what's happening.
whats happening is it goes straight to 5, seems like its running in the background
How are you debugging? What made you come to this conclusion?
Iโm debugging it by checking how many times the coroutine is called
Sorry
I mean what wave itโs on
So it starts from wave 0 and it goes all the way to 5 even with a. Time delay
How? Debug logs?
Yeah using a debug log I check what wave it is before and after the spawn function is called
Share the updated code with the logs
From what I can see, it would wait 3 sec after the game start and then go through a wave each frame.
So basically all 5 waves would be done in a few frames.
So where can I put the delay instead?
How exactly do you want it to work? Just spawn waves with some interval?
like spawn the waves one by one instead of skipping all the way to the 5th
They should be all spawned one by one. Just in a few frames.
thats not whats happening though
Then debug that.
WaveCounter.instance.WaveCount seems to be what devices the wave index.
yes
You want to debug that before the spawning logic.
i have that debugged
Not in update
in the thing that spawns my stuff?
Yes
ah yeah
okay i did that
whats happening is all the waves are spawned immediately all at once
So they do as I said?
yeah
how would i delay it so they dont all spawn at once?
If you just want a delay between the waves, get rid of the coroutine and just use a timer in update.
nvm i fixed it lol
lemme double check tho
@cosmic rain thanks for the help, what i changed was making the isSpawning boolean to true before the delay is started
Hello, i have been having trouble with coding.
In one part of my game, there's a barrier blocking a part of the map which you need the flashlight and yeah that part is working. The problem is that the message displaying telling you to get the flashlight is not appearing. Can someone help me with this?
I don't think that fixes the underlying issue. Just conceals it.
Whats the code you are using and how do you trigger this text display?
idk but the waves do spawn well now, its a school project and ive only been doing unity like for 2-3 weeks lol
Hi guys bit of an interesting question here.
I have a script that generates a random HSL color for my bullets. (cool rainbow bullets)
This script then uses a SRGB difference algorithm I wrote to ensure that there is a noticeable degree of variation between each bullet's color prior to spawn to keep things interesting.
However, I'm still not satisfied with the contrast of the bullet's color and the level, and sometimes there's the issue of the algorithm not understanding that "blue" and "light blue" are still blue even though they pass the sRGB threshold test.
I've thought about having an array, with 256 unique websafe colors to ensure contrast between the level and the bullets, and as well as this, if I order the colors in a JSON file, following a ROYGBIV (red, orange yellow...) rainbow I can calculate different colors by just adding X steps to the JSON array instead of these expensive color algorithms.
My question is:
-
Should I have the JSON file with all the shades of color be on my "game manager" gameObject and have each bullet reference a color that way OR:
-
Include the external JSON file on each bullet and have internal calculations prior to spawning.
-
What would be the most efficient?
-
Is there anything I should worry about if I include a file with cross platform development?
-
Do you have any suggestions for a more efficient approach whilst achieving my above mentioned goals with variation and contrast in mind?
can i just send the code i have?
i am trying to call an OpenAI API like:
-d '{
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Whatโs in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
}
}
]
}
],
}'
here's my 8 hour progress:
https://pastebin.com/Fs8MpWwu (just the relevant parts)
here's my error:
HTTP/1.1 400 Bad Request
line 58 on PasteBin.
don't bother explaining, i know i'm not sending the parameters correctly, but that's the issue...
Sure, you can post your !code with the approaches the bot mentions
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
barrier script: https://paste.ofcode.org/Wy2qBnr7nDVKBBnLRjrN3s
canvas/text script: https://paste.ofcode.org/35NR5wSutU2amc79RgWa5f7
It would make sense to load the json once into an array in a game manager or similar manager class. In fact it might make sense to create a bullet manager that would handle all the logic, like keeping track of what color was used last, etc...
Not sure what you mean by a "file with cross platform development".
I agree that seems to be the best approach.
Well I'm not sure if I want the array of colors to be an external JSON file, or just have a hardcoded array in the manager class.
If I do pick an external file, I'm worried that there might be some issues with how the file is included on linux.
You could just have is a serialized field on the manager. Up to you.
Why would there be an issue with how it's included? If it's part of the build, there shouldn't be any problem at all.
Really? Cool! Thanks again!
I just wasn't sure if I had to chown or chmod the file somehow to ensure permissions did not break.
Looks like your textActive bool is almost always false, the only time it ever becomes true, is if your lanterna reference is not active, then on E input, you destroy the object containing your BarreiraInvisivel script, so your textScript is likely always going to be false in best case, and null in worst case
so how do i fix that?
i am trying to call an OpenAI API like:
-d '{
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Whatโs in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
}
}
]
}
],
}'
here's my 8 hour progress:
https://pastebin.com/Fs8MpWwu (just the relevant parts)
here's my error:
HTTP/1.1 400 Bad Request
line 58 on PasteBin.
don't bother explaining, i know i'm not sending the parameters correctly, but that's the issue...
if thats a curl command which i think it is because of the -d it should be pretty simple to do with pretty much any http client
Assign the bool your checking with, so its not always false, for example you seem to be also using another private bool jogadorPodePassar and your using that to handle checking your input, instead of your public bool
curl https://api.openai.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -d '{
what is the code exactly?
like i said, i've spent over 8:30 hours documenting and trying different stuff out, nothing clicks
The code that you wrote? You linked it, I didnt mention anything that isnt already in your scripts
you just need to figure out how to serialize the body, after that its just add the 2 headers and post
i mean, the new part of the code that you said to change
have you not done similar stuff before? i just want a clue.
Well, look over your BarreiraInvisivel script and see what you are doing with your jogadorPodePassar variable and textActive, knowing that only textActive is accessible outside of your class, and jogadorPodePassar is not, only being used inside your class
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Post.html
more or less follow the example here, but after the post before the SendWebRequest use SetRequestHeader on what post returns to set the bearer token
quick question, have you taken a look at the code i posted earlier, you'll see how stuck i am, and at the same time how close to finishing the whole behaviour.
https://pastebin.com/Fs8MpWwu
i've done this before:
"model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." } ] }'
but not:
"model": "gpt-4-vision-preview", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Whatโs in this image?" }, { "type": "image_url", "image_url": { "url": "blahblhah" }
should i also remove the text script?
Thats up to you in how you want to/have your scene designed
i'm having trouble with the code, could you write part of the code to make it work so i can see how it actually works?
Well, do you understand how your current code works?
most of it, yes. i had a friend's help
Can you explain what your code is doing, and where you think the problematic part is?
that's the thing, it should be working
i don't see where the problem is
Well it does what you wrote it to do, sometimes explaining what you did can help you find the problem, its called a "rubber duck effect"
async Awaitable TimerStart(float startPoint)
{
while(true)
{
Debug.Log(Time.time - startPoint);
await Awaitable.WaitForSecondsAsync(1, destroyCancellationToken);
}
}
```Hey, does this error mean something is wrong or just an info it has been canceled correctly and everything is fine?
It means it was cancelled. You should try catch that specific exception at the point where you want to handle it
try
{
await Awaitable.WaitForSecondsAsync(1, destroyCancellationToken);
}
catch(OperationCanceledException e)
{
Debug.Log("Coroutine canceled successfully: " + e.Message);
}
catch(Exception e)
{
Debug.LogError(e.Message);
}
```Well, I did put a try catch but I'm not just sure if this really is an error and should I do something with it? Or is it fine as it is?
It's probably pointless to catch it there unless you want to continue execution from there?
And no, you generally just catch it and do nothing with the exception, as it's purpose is entirely flow control
No, it seems this exception is being thrown only when I stop the game
Yes, because the object is destroyed then, otherwise it would continue running the async function into edit mode
you should handle it at the top of the async stack, where you start awaiting
so you can cancel out of the logic entirely
Aight, so it's all good even though it shows me "OperationCanceledException" which technically is an error but for us is fine?
Does it matter? Can I catch it inside the method or should I catch when I call the async method?
it's your code, I told you what I would do
An error is generally telling you that something went wrong. When an awaitable did not finish it's execution due to cancellation, it's something went wrong and you need to handle it.
Aight 
OperationCancelledException is not communicating wrong, it's communicating cancellation, nothing more
It didn't finish execution because it's never going to finish it
it's rather going infinitely until I stop the game
I would said it's while(true)
round value is not going to reach 3 anyway in my code
Just edited this code to show what I mean
I wonder why it's different from the C# tasks though. I don't think there's an error when you cancel a task via a cancellation token.๐ค
There is
Hmmm... Don't remember it ever being thrown when I canceled tasks.
https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation
By throwing an OperationCanceledException and passing it the token on which cancellation was requested. The preferred way to perform is to use the ThrowIfCancellationRequested method. A task that's canceled in this way transitions to the Canceled state, which the calling code can use to verify that the task responded to its cancellation request.
It depends entirely if you choose to use the cancellation token this way
and Unity has chosen to do that in their awaitable implementation so you don't have to additionally check and handle it
it's very standard though
Backing out of the whole async stack when the game ends would be a pain in the ass without the exception
I know because I've tried it before lol
async Awaitable TimerStart(float startPoint)
{
float elapsedSeconds;
ushort elapsedMinutes = ushort.MinValue, elapsedHours = ushort.MinValue;
while(round < 3)
{
elapsedSeconds = Time.time - startPoint - elapsedMinutes * 60 - elapsedHours * 3600;
if(elapsedSeconds >= 60)
{
++elapsedMinutes;
elapsedSeconds -= 60;
}
if(elapsedMinutes >= 60)
{
++elapsedHours;
elapsedMinutes -= 60;
}
timer.text = $"{elapsedHours:D2}:{elapsedMinutes:D2}:{Mathf.FloorToInt(elapsedSeconds):D2}";
try
{
await Awaitable.WaitForSecondsAsync(1, destroyCancellationToken);
}
catch(OperationCanceledException e)
{
Debug.Log("Coroutine canceled successfully: " + e.Message);
}
catch(Exception e)
{
Debug.LogError(e.Message);
}
}
}
```Well, that's how I've made it and how it looks like now, during game play, once called it starts counting and showing time in the game and keeps counting infinitely until the game is stopped, so I believe this try catch is all good and no issue here
I really have no idea why you would catch in the inner loop
I usually don't have long chains of a async operations, so it was easy to just return from the sync method on cancellation. But it does make sense.
Well, this exception is going to be thrown at the end of the game, it appears only and every time I stop the play mode
that doesn't justify anything
why are you slapping yourself in the face?
well it's a nice day outside
if(keyboard.rightArrowKey.wasPressedThisFrame)
{
await PlaySound(przejscie);
if(++round == 1)
await TimerStart(Time.time);
}
```So you're saying I'm supposed to do try-catch where I call this async method? Here?
TimerStart()
This sounds like you're running async code in your editor... I'm a bit lost on what you're trying tro achieve in your TimerStart method. Was there anything wrong with using Time.deltaTime?
No, everything works fine but the only thing is when I exit play mode I get this error #archived-code-general message
If that's the top of the async stack, sure, catch it there.
You can also catch it outside of the loop. There's just no reason to catch it inside the loop, just to have it potentially go around the loop again
I think so? I call it inside async void Update()
Alright
thanks for your help!
Async update๐
Actually I just thought I can make some sort of kill switch and instead of while(true) do something like while(!isEscaping) so when user exits the game the bool value stops the loop and finishes the async method
You are running an infinity loops with no breaks. Unity won't close play mode unless it breaks your loop somehow.
Won't close play mode? As I said it's all working fine 
I don't know what's worst... That this update is async, or it's returning void from async method.
The structure of this code is set up to fail because there's variables being relied on to increment and they're not even incremented in the same function that relies on it
Returning void from async is fine in Unity at the top of the async call
Because Unity handles exceptions differently than normal .NET programs
unity's awake method is a void async version ๐ฌ
I use IEnumerator for Awake/Start methods
I can't remember, but won't this suppress exception thrown inside async void methods?
No, because Unity catches it
As long as Task/Awaitable-returning async methods are awaited no exceptions should be eaten
half of Unity's UGS APIs are async Task so gotta use that :\
anyone know what these errors are?
Editor API is not included in the build. When you try to build with code that relies on it, it would fail.
also don't crosspost @zinc knot you already asked in #๐ปโcode-beginner
alr
Does anyone know where to get the information link on creating a 2D Character in a 3D Environment?
Google tutorials.
i'll check that
I dont know where to ask this,
but can someone tell me how maps like this are usually created?
Is a tile system in place? Does it use unity terrain?
The image is from a game called Broken Arrow.
Thanks
man that map is about flat as florida
can look into unity's terrain tool. It's pretty basic but it gets the job done
what would be the optimal solution to anchoring a point to a specific region of a perspective camera using a varying FOV? here's a couple photos based on what we have. the gun camera has an FOV of 75, hence when I make the normal camera FOV 75, it is positioned properly. however, it gets displaced because of the gun cam still being 75, thus changing the position of the origin of the bullet trail in the perspective cam. im assuming i have to use tan in this, but im not sure how. any insight?
75 FOV
120 FOV
in my game i have a levelManager script that handles values like wave, lives, etc and passes them to an additive UI scene to display it on the HUD. would i have any issues using a scriptableObject as a data middleman here where levelManager updates the values every frame and then a UIManager script in the other scene grabs those values and updates the UI?
assuming you are using two camera, how about using guncamera.worldtoviewportpoint then use the return value to camera.viewporttoworldpoint?
yeah I thought of that, but what about depth, isnt that a vector2?
because perceptual distance also varies with fov
it's vector3, with z is the distance from camera
https://docs.unity3d.com/ScriptReference/Camera.WorldToViewportPoint.html
anyone know how to fix these kind of dash? I tried multiplying it by time.deltatime but it didnt work
here is my code
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi. I'm building and then trying to install two different apps from one unity project on android. But my phone still detects them as "same app" and making an update instead. How does android differentiate one app from another and how to fix my problem?
With the bundle identifier
You need to change it to com.company.app1 and then for the scond build do like com.company.app2
thank you
When doing an asynchronous load scene, can I make it only prepare the load, then I make it load ?
By default when doing AsyncLoad it will directly load when finished
Ty
hey dude just wanted to so that i think i sorted it out, had a good look at many repos and in the end i decided to go for this one https://github.com/NavidK0/SimpleGraphQL-For-Unity
the reason why i didnt want to use packages such as the above is becuase most of them dont support subscriptions on webgl builds but i have found a work around that. i still dont get some of the data but i do get most of it so hopefully all should be good from now on and again thanks for the time you spent trying to help me it was appriciated
Good to hear. Subscriptions for WebGL should not be a big problem, just need an Emscripten .jslib to act as a passthrough from the browser JS to Unity.
As this library looks to be abandonware I may incorporate all of parts of it into my SQL for Unity system as an addon feature
i am not really allowed to disclose much but i am working with a library that connects to another engine that came out literally 1 week ago and i am the only one debugging/testing, this lib i am using does have subscription and queries function for graphql as that is sort of how that engine works but its really not the best, but i have managed to get the subscriptions to work through that lib and then i will use general queries through https://github.com/NavidK0/SimpleGraphQL-For-Unity here, bit messy but when you are the first in this sort of things its just how it is. i hope this gives a bit more context to the whole thing i have been through
Best of luck with it, one question though, how is the performance? That has always been my biggest problem with any kind of NoSQL integration into game dev
i have never had any issues with speed on the react end even with 1000+ entities getting updated, but i have to yet migrate everything to unity i am still doing basic tests to see if all the basic functions work but i will let you know
please do
Hi, so I have this struct which is holding data for my conveyors. However I need to keep a float3 array for different paths. Can I use native arrays for this or would it result in a data leak? I also get an error which says Unity.Collections.LowLevel.Unsafe.DisposableSentinel, which is neither primitave nor unsafe.
Native data is unmanaged data so you are responsible for disposing of it, not doing so will result in memory leaks
You should probably be asking in #1062393052863414313 as you are using ECS
Hi I'm implementing basic dragging and dropping of UI elements. What is the 'best practice' way of checking if the Collision2D being overlapped contains a specific component. Running GetComponent<>() on every collision frame seems horribly inefficient, and using tags feels like jank.
uh.. what?
this line has the issue
im setting my action.. to a void that matches the parameters required
what tf is this error
oh i think eventExposer was null
a nullreferenceexception wouldve made that clearer wtf is this one
to all you people who insist in posting screenshots of code, the least you can do is INCLUDE THE BLOODY LINE NUMBERS
No
Be mindful, if someone requests your code as text, don't send a screenshot!
they just ignore it
i highlighted the line in the error
Hi everyone. I have a strange issue. I got a coroutine Invoking an event, but the code after the Invocation isnt executed. This is my code. Any Help would be much aprreciated ```cs private IEnumerator CameraTransition(Material mat, MovementType movement)
{
cameraAnimator.SetTrigger("FadeOut");
LocationManager.Instance.PointChange?.Invoke(movement);
yield return new WaitForSeconds(1);
RenderSettings.skybox = mat;
cameraAnimator.SetTrigger("FadeIn");
}```
I would guess an exception is being thrown
Either the coroutine isn't started correctly, or the object that started it is destroyed during the one second it pauses
No not at all. No error appears. All the execution of the project after that is working fine, but the code in coroutine after the invocation isnt working
debug it
the coroutine is called with StartCoroutine and there is no Destruction of anything.
I have debuged it and I ve set a break point in the Invocation. The next step just skips the code after the invocation
And the MonoBehavior the coroutine is associated with isn't modified in any way? Disabled or such?
No
Show full code
Aaaah
this might be the issue
I sorted it out. Thank you all for your valuable feedback @mellow sigil @sacred plaza @knotty sun
How do I export data (here .zip) during runtime?
I want that my bugtesting exports the persistend data I am saving in userdata. They should be able to save it anywhere on the iPad so they can send me it in discord
you can easily create a zip file using
https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfile?view=net-8.0
however you can only save to Application.persistentDataPath, not 'anywhere'
yeah yeah I am already saving json and zipping the folders. What I want is that the users can send me zip, export it out of persistent data
Guess I need a file browser or some sort
that's easy to make with the UIToolkit TreeView
I have a concern regarding optimization
Context:
my game have rooms procedurally generated, the rooms floor and walls(no roof) are made of multiple individual cubes. the camera is orthogonal top-down rotating around the player as center point
I have 4 directions (normalized) the camera can rotate to defined as
"North" is (1,1 )
"South" is (-1,-1 )
"East" is (-1,1)
"West" is (1,-1)
When the camera is facing from the north direction, i want to hide the north walls of every room, meaning i have to loop the collection to SetActive(false) each cube. To separate the walls of each room based on the cardinal direction, i placed the "cardinal axis" (0,0) on the center of my rooms and normalize the position of each cube, using the wall.height to determine the corners directions.
Issue:
The issue is regarding which data structure would be the best performance wise in this case, the most direct approach would be to have 4 different arrays such as:
int wallArea= (averageWall.height * averageWall.length) * (RoomList.Count*4)
Cube[] NorthWalls= new Cube[wallArea];
Cube[] SouthWalls= new Cube[wallArea];
Cube[] EasWalls= new Cube[wallArea];
Cube[] WestWalls= new Cube[wallArea];
but because some walls will be bigger than others, the arrays might have empty spaces, there's also matrix, or dictionary approach:
directionMap = new Dictionary<string, Cube>();
// and then to add the cubes would be something like this. In this case, checkDirection would return a string of the cube direction like "North", "South", etc.
void PlaceWallCubes(Vector2Int location, Material material) {
for(int i = 1; i < wall.heigth; i++){
GameObject go = Instantiate(cubePrefab, new Vector3(location.x, i, location.y), Quaternion.identity);
directionMap.Add(CheckDirection(go),go);
If you only change whether a wall is active or not when the camera is rotated, you can pretty safety iterate over every wall in the game when the camera has been rotated for a certain threshold for a really large number of walls.
But, if you want a more optimised method you could build an index ahead of time. Which is just four arrays referencing the walls. I am not entirely sure why the size of the walls matter, I'd expect each wall segment for a cardinal direction you'd want to hide to be part of some distinct object hierarchy (which is just one reference) so you'd use that.
why your array can have "empty space"
btw i think you will get "duplicate key exception" (i forgot the name) if you use dictionary
you dont need any of this, let each wall 'think' for itself
wdym "think" for itself? can you explain more?
let each wall subscribe to an event, say CameraChange.
when the camera changes invoke the event, then each wall can decide whether it should be visible or not and take the appropriate action
Thats far from optimal imho. Depends on how many walls he has
the ammout of processing is identical if not less
the area is to have a precise array lenght because the walls are made of cubes, i'm adding the cubes to the arrays, not the object "wall"