#archived-code-general

1 messages ยท Page 261 of 1

odd arrow
#

nah bc that takes full png or jpg bytes

#

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

spring flame
#

[ScriptedImporter(1, "someExtension")], that's how importers are annotated and unity later knows which importer to use for which kind of asset

leaden ice
odd arrow
#

unrelated though is it not? still have to save that Texture2D asset to exist in the asset browser either way

spring flame
# odd arrow

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)??

odd arrow
odd arrow
#

for purposes other than wanting the extra texture import settings, my code works perfectly fine for pixel data n all that

leaden ice
#

hmm maybe not actually

spring flame
#

To my current understanding, if you want to use the TextureAssetImporter, you have to use the filetape that this importer supports

leaden ice
#

yeah if you just want a serialized .asset containing a Texture2D you use CreateAsset

spring flame
#

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

odd arrow
#

ughhh TextureImporter is sealed

fossil steeple
#

@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;
            
        }
    }
spring flame
#

welp, then I guess going with the route of supported asset types is the best option

odd arrow
#

yeah unfortunately

leaden ice
odd arrow
#

sadly that's probably the only option ugh!!!

spring flame
#

I don't quite understand what's so bad with that, why do you try to avoid having .png and want to keep .asset ๐Ÿ˜… ?

odd arrow
#

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

leaden ice
deft dagger
#

hey, why doesnt this code work ?
var content = JsonUtility.ToJson(userPost);
Debug.Log(content);

rigid island
odd arrow
#

the pixel loading is irrelevant to this but i appreciate the help

#

imma probs just suck it up and live w/o import settings

deft dagger
#

the debug log thing just prints: {}

leaden ice
#

or has no serialized members

rigid island
#

something you trying to serialize maybe isn't serializable

#

yup

rigid island
#

show userPost obj

deft dagger
#

this is the class of userpost

leaden ice
#

those are all properties

#

it can only serialize fields

rigid island
#

much better

#

JsonUtil is garbo

deft dagger
leaden ice
#

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;```
leaden ice
#

is there a good reason you need them to be properties? They seem to all just be autoproperties

fossil steeple
deft dagger
leaden ice
leaden ice
deft dagger
#

but because it gives an empty object its returning an error that they are empty

leaden ice
#

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

deft dagger
#

so i should just delete the get set ?

leaden ice
#

that's the easiest/simplest way forward, yes.

deft dagger
#

i see

rigid island
deft dagger
#

i will try that now, thanks

rigid island
#

keep in mind with jsonutil , if you use dictionaries you need another workaround

leaden ice
round violet
rigid island
leaden ice
#

if you just want ray from the center of the camera you can do this:

Ray r = new Ray(camTransform.position, camTransform.forward);```
rigid island
#

@fossil steeple ^^ this

leaden ice
# round violet any ideas ?

either selectables is nuill or selectables[_currentSelection] is null. Find out which with some log statements or the debugger

round violet
leaden ice
round violet
#

i just edited the code by adding more list entries and now its not working (or maybe its the panel ?)

leaden ice
#

When your code is erroring, it's either on a different instance, or at a different time when there are null entries

round violet
#

i only have 1 instance of this mainmenu

leaden ice
#

YOu are still skipping the very first step of debugging here

#

figure out exactly what is null

round violet
#

well its the lists entries

leaden ice
#

add debug logs or attach a debugger

leaden ice
rigid island
#

^^ debugger is your best friend

leaden ice
#

it could be the list/array itself

round violet
leaden ice
round violet
#

then if its null, why is it showing the correct data in the inspector at all time ?

fossil steeple
#

@leaden ice
How am I gonna ignore my player this way though?
since my camera is set to look at my player all time

leaden ice
#

Rule #1 of debugging is to quiestion your assumptions

deft dagger
fossil steeple
leaden ice
round violet
#

so i dont see why the entries becomes null

round violet
leaden ice
#

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

round violet
#

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);
        }
round violet
leaden ice
rigid island
round violet
#

im sorry if i appeared rude, ty for helping out

heady iris
#

as Sherlock once said:

#

When you have eliminated all which is impossible, then whatever remains, however improbable, must be the truth

knotty sun
round violet
heady iris
#

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.

knotty sun
#

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

round violet
#

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

knotty sun
round violet
#

how can you debug the instance id ?

rigid island
#

make debugger your best friend

knotty sun
heady iris
#

every unity object has an instance ID on it

round violet
#

that great, didnt know it existed

knotty sun
lean sail
#

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

lilac burrow
#

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.

lean sail
old coral
#

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

timid pebble
#

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

cosmic rain
foggy phoenix
#

Question on Pac-Man Clone Based on Guide Playlist

rigid island
rigid island
#

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

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

quartz folio
quaint rock
#

yeah it was only dropped for a bit till ms picked it up themselfs

#

though i am partial to team Rider here

rigid island
#

yeah Microsoft but Unity for some reason doesn't care to support it even though they use it themselves lol

quaint rock
#

why spend the resources is MS alreayd is

rigid island
#

Microsoft made smart move for market share

quaint rock
#

the Rider one is also included in the package manager too but is all maintained by jetbrains

rigid island
#

Devkit after all is a licensed product like VS

bold wraith
#

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.

rigid island
bold wraith
#

do you know how to solve the problem?

bold wraith
#

that part is what I have of parameters

rigid island
bold wraith
#

that's what I have set

rigid island
bold wraith
rigid island
quaint rock
bold wraith
#

is that it?

rigid island
#

thats the Animator Controller mate

#

the Animator is on the gameobject itself

bold wraith
#

this one?

rigid island
#

and yea thats the one

#

character_animator1 vs player.controller

bold wraith
rigid island
# bold wraith

SpriteDirectional is the script thats causing those warnings?

bold wraith
#

Yes.

rigid island
bold wraith
#

ok

#

copy and paste a screenshot is ok?

proper imp
#

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.

rigid island
tawny elkBOT
bold wraith
#

did that link work?

rigid island
#

yup just checking if maybe you had start method that was doing GetComponent

bold wraith
#

ok

rigid island
#

you do have the wrong controller on player

bold wraith
#

what is the right controller for player?

rigid island
#

the one called Player

bold wraith
#

and set it to the sprite directional controller?

rigid island
#

no not sure where you even have this Animator at, use the one already on player and replace the one there

bold wraith
#

check me if I have all the scripts I need

#

one moment

#

to create a basic

rigid island
#

Idk i guess this doesn't tell me anything

bold wraith
#

oh

rigid island
#

kinda irrelevant to your fix though lol

bold wraith
#

ok where do we continue?

rigid island
#

dang.. you really need some Unity basics

#

!learn

tawny elkBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

bold wraith
#

this script is so rare though

rigid island
#

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

bold wraith
#

that it?

rigid island
rigid island
bold wraith
#

by the text of it

rigid island
#

the text is irrelevant if its the one on the wrong object

bold wraith
#

ok ill make it larger

rigid island
#

ok, clear the console first and then run the game see if its gone

bold wraith
#

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

rigid island
#

sounds like you should learn how to use Version Control

bold wraith
#

ill check into that

#

does it cost money?

bold wraith
#

ok ill look at that later thoroughly

#

ty\

rigid island
#

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

bold wraith
#

i did quite a few amount of times on that unity learn option

#

stuck on graphics

#

ill eventually continue that

rigid island
#

wdym by Graphics

bold wraith
#

the third portion

#

"Creative Core"

#

I also have Udemy.

#

is it possible to get this guy moving tonight?

rigid island
bold wraith
#

debugging I am committed to doing

#

I assume that the player controller doesn't have keys setup

#

the input of " w a s d"

cosmic rain
#

I thought you had an issue with the animation? What do the controls have to do with it?

bold wraith
#

the animation is created, but the keys don't seem to do anything when I press them

cosmic rain
#

Maybe start from explaining the issue in details before moving on to debugging. Share a video of it if words are not enough.

rigid island
bold wraith
#

ok lets get the code adjusted then?

rigid island
#

you have to code stuff in its not magically there

bold wraith
#

i remember setting up a controller, but it took some time

#

isnt there a package of it?

rigid island
#

there is a built in Input class

#

there is also a newer Input System unity released as package

bold wraith
#

whats the name of that?

rigid island
#

the name of what ? Input System, I just said it lol

bold wraith
#

ohh

cosmic rain
#

The input system is not gonna add character controller logic for you. You have to code that.

rigid island
#

I wouldn't worry about that now, learn the "traditional" way first

bold wraith
#

okay

#

i installed the input system for later

#

where can we start the code at?

cosmic rain
#

Start by going through unity learn or looking up a tutorial for a character controller that suits your need.

bold wraith
#

ok brb

thin shoal
#

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

rigid island
thin shoal
#

does unity have that built in?

rigid island
rigid island
thin shoal
#

so not built in

#

if it in a plugin scenario

rigid island
thin shoal
#

strange, unity have addressable but don't have a system that checks for storage

rigid island
#

uinty also has code to open file/directory dialog for editor only, but not for the build.

#

gotta take what you can ๐Ÿคทโ€โ™‚๏ธ

zinc knot
rigid island
#

also that happens because light wasnt generated so light data is missing

twilit scaffold
#

is [SerializeField] somewhat new? I am seeing most tutorials just use public for things that should be serialize field

quartz folio
#

No

#

Tutorials are bad/avoiding it for supposed simplification

bold wraith
#

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

โ–ถ Play video
broken jewel
#

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

cosmic rain
broken jewel
#

remove instance(j)?

cosmic rain
#

Oh, you're using it there.

#

What exactly doesn't work?

broken jewel
# cosmic rain What exactly doesn't work?

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

bold wraith
frosty snow
#

ok i finally got a basic scripting system working

bold wraith
#

I added an Xbox controller to it, but doesn't work to operate a sprite to me yet.

cosmic rain
broken jewel
#

it somehow doesnt ๐Ÿ™

#

those little kids are the extracted ones

cosmic rain
# broken jewel

How are they supposed to look? And is the prefab scaled as 1 1 1 by default?

broken jewel
#

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

cosmic rain
#

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.

broken jewel
#

im not good at coding, could you just guide me where to modify?

cosmic rain
#

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

tawny elkBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

broken jewel
#

thank you

broken jewel
faint tree
#

anyone know how to list files in firebase storage?

junior wind
#

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

latent latch
#

can you explain the issue more beyond it just not working

junior wind
#

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

lunar python
#

why dont you just use a spin function using mathematics instead of relying on circle collider

junior wind
#

the collider acts as the trigger for the rocket to begin orbiting a planet

latent latch
#
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

junior wind
#

already doesn't like it in 2d :/

latent latch
#

it's just an alternative though from rotatearound but it's basically similar logic if you wanted to know how it worked

junior wind
#

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?

latent latch
#

wouldn't it be z that you rotate around

#

rather, the axis of rotation

lunar python
#

why arent we using the standard matrix multiplication to orbit the object

junior wind
junior wind
latent latch
#

right, you set your look direction too

#

or by the cross product

lean sail
#

Matrix multiplication alone means nothing here though, i assume you mean transformation matrix

latent latch
#

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.

junior wind
#

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

latent latch
#

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

junior wind
#

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

lunar python
#

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

lean sail
#

Orthogonal just means dot product is 0

#

2 orthogonal 2d vectors would just span the 2d space

lunar python
#

all of my rigidbody is kinematic so I have to configure my own physics system

#

kinda annoying but more choices

latent latch
#

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

lean sail
# junior wind I X J = K, no?

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.

junior wind
#

okay my bad, I'm probably all over the place as I'm trying to learn how to incorporate these concepts

lean sail
#

Either you are referring to some advanced graduate level concept beyond my knowledge, or have a big misunderstanding ๐Ÿ˜…

junior wind
#

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

lean sail
latent latch
#

probably want to check distance before rotating

#

use OnTriggerStay

junior wind
latent latch
#

then check inside of it

junior wind
#

there we go

latent latch
#

this with rotatearound? Doesn't seem to keep the direction either

junior wind
#

yeah this is with rotatearound

latent latch
#

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 ;)

junior wind
#

๐Ÿค”

latent latch
#

but otherwise the object's rotation doesn't matter

junior wind
#

what do you mean?

latent latch
#

rotatearound just lerps a position around a point without any regards for the rotation

#

like, you're not applying forward velocity anywhere here

junior wind
#

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

latent latch
junior wind
#

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?

latent latch
#

yeah, and then you can probably just define the orbit radius per planet

junior wind
#

cool, I'll give it a shot

latent latch
#

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

junior wind
#

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.

latent latch
#

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

junior wind
#

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 ๐Ÿ˜“

latent latch
#

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

junior wind
#

Thanks Mao

sand vine
#

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

sand vine
#

I tried this but doesn't work for me sadly. I can pass only horizontal axis, i need something specifically for right side drag

knotty sun
#

then you have probably anchored your rect transform incorrectly

sand vine
#

True, i had my x pivot on 0.5 ๐Ÿคฆโ€โ™‚๏ธ

Thank you very much ๐Ÿ™‚

sacred zenith
#

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?

lunar python
#

my code messiness is scaling very quickly ๐Ÿ”ฅ

dawn nebula
#

nice

timid depot
#
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
knotty sun
#

instead of
print(waterLevel);
use
Debug.Log($"{GetInstanceId()} {waterLevel}");
this will show if there are 2 objects

timid depot
#

ok give me a second

#

sorry I added script twice

#

thanks for your help

dawn nebula
#

How often do you guys set component references in the inspector as opposed to using GetComponent in Awake/Start?

dawn nebula
fringe ridge
#

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

quaint rock
#

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

lunar python
#

what is selectable tiles

#

isn't tile pallete very sufficient (idk)

hard viper
#

tile pallette only works in Unity editor

fringe ridge
#

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

quaint rock
#

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

fringe ridge
#

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.

slow shale
#

Im getting an error trying to save a file: UnauthorizedAccessException: Access denied
File.WriteAllText(Application.dataPath, json);
How do i fix this?

fringe ridge
#

and for keeping track of the cells i have a list of cell objects

slow shale
#

regular windows

rigid island
quaint rock
#

Really no runtime code should ever need to hit the dataPath

slow shale
quaint rock
#

No unity provides a path

#

Application.persistentDataPath

#

Look up it's docs

slow shale
rigid island
#

well give it a filename

slow shale
#

"C:/Users/Uporabnik/AppData/LocalLow/DefaultCompany/Potapljanje" that is a file name tho, i just checked it exists

rigid island
#

thats a folder of your project appdata

slow shale
#

oh im stupid

heady iris
#

you need to join it with something else to get a file name

rigid island
#

Path.Combine(Application.persistentDataPath, filename)

slow shale
#

yep, i followed a tutorial and missed the main part, sorry, thanks tho

lament epoch
#

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
                ]
             ]
quaint rock
#

pretty sure both float[][] and List<List<float>> will work

#

though do you want float or int, since the data has no decimals?

lament epoch
rigid island
#

or make it a custom class/struct no? then a list of it

quaint rock
#

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

late lion
#

Unity's serializer doesn't support directly nested arrays/lists. You have to wrap it in a serializable class/struct.

quaint rock
#

well i am making the assuption this is not unitys but like json.net

rigid island
#

maybe

quaint rock
#

which i heavily recommend to use over JsonUtility, its a more more complete implementation of json with way less gotchas

lament epoch
#

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]);
    }
quaint rock
rigid island
#

Ahh ok just doing a quick thing , haven't caffeinated yet so prob is wrong ๐Ÿ˜…

quaint rock
#

since the inner items also use [] so are not structs

rigid island
#

ahh i see

quaint rock
#

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

lament epoch
#

ok thanks for your help I will try that

heady iris
#

I have a bunch of "Identifiable" scriptable objects that all have GUIDs stored in them

quaint rock
#

if the List<List<float>> does not work, its because of a limitation in JsonUtility

heady iris
#

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)

quaint rock
heady iris
#

or maybe I'll just go straight to a binary format. who knows

quaint rock
#

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

lament epoch
#

im not that experienced. I have no idea what you guys are talking about haha

heady iris
#

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);
lament epoch
#

ok ill see what i can do but thanks again

rigid island
#

JsonUtility is ok for basic stuff but its total crap for everything else

quaint rock
heady iris
#

now that's a new one

#

github forgor the page

#

(it's good now)

quaint rock
#

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

ornate scroll
#

somebody help me?
the object not accompanies the character's hand

west lotus
hoary sparrow
#

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);
}```
leaden ice
#

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

hoary sparrow
leaden ice
#

What debugging steps have you taken so far?

leaden ice
hoary sparrow
gray mural
#

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);
rigid island
gray mural
#

I just wanna find Images even with Raycast target set to false

rigid island
#

images from where and why does raycast target need to be off?

leaden ice
#

What are you trying to accomplish?

lethal dragon
#

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

heady iris
#

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
lethal dragon
#

ive implemented this and its still not working

heady iris
#

then show your code

#

i have no idea what you've actually written

leaden ice
lethal dragon
#

heres my code where path is application.datapersistent and filename is data.game

#

thats the error

leaden ice
#

Where did you get path from?

heady iris
#

That is not Application.persistentDataPath

leaden ice
#

that path doesn't look like Application.persistentDataPath at all

#

That looks like possibly Application.dataPath

lethal dragon
#

thats where im actually calling the class filehandler

heady iris
#

that doesn't show us where path comes from at all

leaden ice
lethal dragon
quaint rock
#

why such a complicated setup for just reading a file

heady iris
#

you can just use File.ReadAllText, yeah

#

I used to use exactly that setup until I realized there's a simpler way

quaint rock
#

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

lethal dragon
#

oh okay thank you

quaint rock
#

could be reduced to just the File.ReadAllText followed by the FromJson

heady iris
#

I'm still confused by your persistent data path, though

#

It's supposed to point into AppData

quaint rock
#

whats it pointing to?

heady iris
#

a folder in the user directory that ain't AppData

quaint rock
#

that looks like its dataPath

heady iris
#

it's like it neatly skipped over AppData/LocalLow/

quaint rock
#

not persistientDataPath

#

assuming thats where the project files are

heady iris
#

Perhaps there are multiple things creating FileDataHandlers or something

#

or the code hasn't been saved

quaint rock
#

would assume that

heady iris
#

so unity is running something old

lethal dragon
#

i dont think my unity is fully updated should i update it and also check where the project is saved?

quaint rock
#

this has worked the same for literally every unity version

heady iris
#

log Application.dataPath and Application.persistentDataPath as a sanity check

quaint rock
#

would just make sure you are infact running the new code

heady iris
#

Okay, it's not trying to open a file in AppData

#

You must have had Application.dataPath previously

lethal dragon
#

okay, what do i need to do?

heady iris
#

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

simple egret
#

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.

heady iris
#

Ah, good point

quaint rock
#

for this case would restart unity and use File.ReadAllText in the future

heady iris
#

yeah, that'll ensure the handle is closed for you

#

(i hope)

quaint rock
#

but if you do need to open file streams in the future i would always put it in a try/finally

heady iris
#

using cleanly handles that for you (:

quaint rock
#

so the finally clause can close things, or let using dispose it

#

does using still work on exceptions?

quaint rock
#

cool

heady iris
#

You can use both a using statement and a using declaration

simple egret
#

It compiles to a try-finally

heady iris
#

The declarations are particularly slick

#
using whatever = ThisMustBeDisposed();
quaint rock
#

yeah the inline one is nice

#

just dispoes on end of function scope

heady iris
#

I use the statement form for IMGUI

#
using (var _ = new GUILayout.AreaScope(new Rect(10, 10, 300, 300)))
{
  // IMGUI in here
}
quaint rock
#

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

leaden ice
#

defer is magic and so much more flexible/useful than try/catch

quaint rock
#

@leaden ice familar with Go, or a other langauge that uses defers

leaden ice
#

I use Go professionally

quaint rock
#

nice, its amung my favourite languages to work in at the moment

gray mural
# leaden ice What are you trying to accomplish?

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?

leaden ice
#

you're writing a lot of code to basically recreate the event system's default behavior

#

It has built in drag/drop support

gray mural
leaden ice
#

I bet it would work fine

#

what does stretching threshold mean?

gray mural
leaden ice
#

So you're saying event system won't work because you want to be able to start the drag from outside the border?

quaint rock
#

you can manually raycast from the event system

gray mural
#

so cursor is gonna be activated and it doesn't care wether there are some other objects nearer to the camera

gray mural
quaint rock
#

so you could start it based on what ever input you want to start the drag, and just manually cast looking for hits

gray mural
#

I have implemented that already, so that's no problem

lethal dragon
heady iris
#

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

quaint rock
heady iris
#

that too

gray mural
quaint rock
#

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

gray mural
#

I haven't mentioned that, because I thought I should've used it for objects without Raycast Target

lethal dragon
quaint rock
#

so you have not executed the code to create it yet, since fixing the path

heady iris
#

your code checks if File.Exists returns true, so it's gotta be seeing something

lethal dragon
#

the error is still showing

#

is there any problem with my save code

knotty sun
heady iris
#

there you go

#

this creates a folder named data.game

heady iris
lethal dragon
#

wdym

heady iris
#

I mean exactly what I wrote. There's a folder named data.game in AppData/LocalLow/DefaultCompany/Shooter Game/, isn't there?

lethal dragon
#

yes there is

heady iris
#

don't create a directory with fullPath.

leaden ice
#
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

heady iris
#

you can use Directory.Exists if you really want to

#

but yes, it's fine if you create a directory that's already there

knotty sun
#

tbh, the complete code is nonesense

heady iris
#

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

heady iris
#
    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

leaden ice
#

You can remove the if check here too:

if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);```
heady iris
#

I was thinking about that

#

went and looked it up and it's like mkdir -p

leaden ice
#

yep

heady iris
#

just didn't actually change it

#

I use onlyCreate to generate a settings file on first launch

knotty sun
lethal dragon
heady iris
#

i build the path out of one or more strings

#

I did flip-flop on that several times, though (:

lethal dragon
#

is this still wrong?

heady iris
lethal dragon
#

oh god

heady iris
#

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

lethal dragon
#

oh

#

okay

heady iris
#

The rest looks reasonable enough. You will want a way to indicate to the player that saving failed, though.

lethal dragon
#

the saving still fails

knotty sun
#

he said PAY ATTENTION

lethal dragon
#

im trying

knotty sun
#

look at the file you are trying to write

heady iris
#

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

lethal dragon
#

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

knotty sun
#

think

#

this is the problem with spoonfeeding @heady iris

heady iris
#

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

lethal dragon
#

i really don't know where the error is i'm sorry im really struggling to see what i'm doing that's wrong

heady iris
#

There are only five meaningful lines of code in that function.

knotty sun
#

ask yourself which variable contains the directory and file name you want to write

heady iris
#

Don't just stare at it.

heady iris
quaint rock
#

its just about attention to detail, regardless of if you stick with programming or not, its a good skill to have

heady iris
#

prove to yourself that every variable and every function call makes sense

quaint rock
#

think about what each line does, and what each variable repersents

stuck lotus
#

Hello, has anyone here worked with a graphql database by any chance?

knotty sun
stuck lotus
stuck lotus
knotty sun
#

should return json or xml

stuck lotus
#

it should return json

knotty sun
#

then the end points have not been configured correctly

stuck lotus
knotty sun
#

that makes no sense, end points do not respond differently depending on the user agent

knotty sun
#

then you need to question your query

#

graphql queries are notoriously fickle

stuck lotus
stuck lotus
knotty sun
#

look very carefully at how you have composed your query, one simple mistake can invalidate the whole query, the joys of json formatting

stuck lotus
knotty sun
#

but really this is outside of the scope of a Unity server

simple egret
#

Maybe you're not passing the correct Accept header? Or no header at all

stuck lotus
knotty sun
stuck lotus
knotty sun
#

what I am saying is take Unity out of the equation. Make something that works first, then transfer that to Unity

stuck lotus
knotty sun
#

exactly, I said use Http Client

stuck lotus
knotty sun
#

but react is not C#

stuck lotus
#

i know that but surely that shouldnt really matter as its just a request right?

knotty sun
#

yes, it matters

#

'just a request' how to say 'I know nothing about http programming'

simple egret
#

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

knotty sun
#

almost definitely the html is an explanation of the http error code, probably 403, 404 or 500

stuck lotus
knotty sun
#

nah

sharp agate
#

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

rigid island
#

turn off filtering and compression

sharp agate
rigid island
sharp agate
#

is just that

stuck lotus
sharp agate
#

i didn't know

#

thanks

rigid island
#

u good np ๐Ÿ™‚

stuck lotus
#

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

knotty sun
#

is that supposed to be a valid query?

stuck lotus
simple egret
#

Post the HTML/XML you get when querying from Unity

#

Alternatively you can open your browser's dev tools and inspect network traffic there

stuck lotus
knotty sun
#

as this is a code channel you could actually just share the code you are using

stuck lotus
#

fair enough give me a sec

simple egret
tawny elkBOT
knotty sun
simple egret
#

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

stuck lotus
simple egret
simple egret
#

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

knotty sun
stuck lotus
knotty sun
#

sure

simple egret
#

I see your code, it's the value of graphqlEndpoint that's incorrect

stuck lotus
#

this is on the react end this works fine

knotty sun
# stuck lotus 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

simple egret
#

If the query was incorrect it would have not returned HTTP 200

knotty sun
#

it did not see the query

simple egret
#

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

knotty sun
#

agreed

stuck lotus
#

ok i will see what i can do, thanks anyway for the time it was appreciated

knotty sun
zinc knot
#

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

cosmic rain
zinc knot
#

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

cosmic rain
#

Do proper debugging to see what's happening.

zinc knot
#

whats happening is it goes straight to 5, seems like its running in the background

cosmic rain
zinc knot
#

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

cosmic rain
#

How? Debug logs?

zinc knot
#

Yeah using a debug log I check what wave it is before and after the spawn function is called

cosmic rain
#

Share the updated code with the logs

zinc knot
#

It goes from 0, to the max in my array, 5 instantly

#

here

cosmic rain
#

So basically all 5 waves would be done in a few frames.

zinc knot
#

So where can I put the delay instead?

cosmic rain
zinc knot
#

like spawn the waves one by one instead of skipping all the way to the 5th

cosmic rain
#

They should be all spawned one by one. Just in a few frames.

zinc knot
#

thats not whats happening though

cosmic rain
#

Then debug that.

cosmic rain
#

WaveCounter.instance.WaveCount seems to be what devices the wave index.

zinc knot
#

yes

cosmic rain
#

You want to debug that before the spawning logic.

zinc knot
#

i have that debugged

cosmic rain
#

Not in update

zinc knot
#

in the thing that spawns my stuff?

cosmic rain
#

Yes

zinc knot
#

ah yeah

#

okay i did that

#

whats happening is all the waves are spawned immediately all at once

cosmic rain
#

So they do as I said?

zinc knot
#

how would i delay it so they dont all spawn at once?

cosmic rain
#

If you just want a delay between the waves, get rid of the coroutine and just use a timer in update.

zinc knot
#

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

lone narwhal
#

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?

cosmic rain
soft shard
zinc knot
nimble cairn
#

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?

lone narwhal
fathom sinew
#

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

soft shard
tawny elkBOT
cosmic rain
nimble cairn
cosmic rain
cosmic rain
nimble cairn
#

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.

soft shard
fathom sinew
#

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

quaint rock
#

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

soft shard
# lone narwhal so how do i fix that?

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

fathom sinew
fathom sinew
soft shard
quaint rock
#

you just need to figure out how to serialize the body, after that its just add the 2 headers and post

lone narwhal
fathom sinew
soft shard
quaint rock
fathom sinew
fathom sinew
#

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" }

lone narwhal
soft shard
lone narwhal
soft shard
lone narwhal
soft shard
lone narwhal
#

i don't see where the problem is

soft shard
fickle lichen
#
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?
quartz folio
fickle lichen
quartz folio
#

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

fickle lichen
quartz folio
#

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

fickle lichen
fickle lichen
quartz folio
#

it's your code, I told you what I would do

cosmic rain
#

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.

fickle lichen
quartz folio
#

OperationCancelledException is not communicating wrong, it's communicating cancellation, nothing more

fickle lichen
#

I would said it's while(true)

#

round value is not going to reach 3 anyway in my code

fickle lichen
cosmic rain
quartz folio
#

There is

cosmic rain
#

Hmmm... Don't remember it ever being thrown when I canceled tasks.

quartz folio
#

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

cosmic rain
#

Ah, so it's users choice how to cancel it.

#

I see

quartz folio
#

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

fickle lichen
#
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
quartz folio
#

I really have no idea why you would catch in the inner loop

cosmic rain
fickle lichen
quartz folio
#

that doesn't justify anything

#

why are you slapping yourself in the face?

well it's a nice day outside

fickle lichen
# quartz folio that doesn't justify anything
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()

plucky karma
#

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?

fickle lichen
quartz folio
#

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

fickle lichen
#

Alright pepeThink thanks for your help!

cosmic rain
#

Async update๐Ÿ™€

fickle lichen
#

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

plucky karma
fickle lichen
plucky karma
quartz folio
#

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

rigid island
plucky karma
plucky karma
quartz folio
#

No, because Unity catches it

#

As long as Task/Awaitable-returning async methods are awaited no exceptions should be eaten

rigid island
zinc knot
#

anyone know what these errors are?

cosmic rain
rigid island
zinc knot
#

alr

bold wraith
#

Does anyone know where to get the information link on creating a 2D Character in a 3D Environment?

bold wraith
#

i'll check that

rancid frost
#

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

latent latch
#

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

fair mural
#

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

long scarab
#

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?

topaz pond
#

anyone know how to unlock these folders?

#

i cant access em

mild coyote
fair mural
#

because perceptual distance also varies with fov

mild coyote
fair mural
#

oh. i was thinking about screenspace

#

thanks

west nova
#

anyone know how to fix these kind of dash? I tried multiplying it by time.deltatime but it didnt work

#

here is my code

cosmic rain
tawny elkBOT
thin kernel
#

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?

west lotus
#

You need to change it to com.company.app1 and then for the scond build do like com.company.app2

thin kernel
#

thank you

round violet
#

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

round violet
#

Ty

stuck lotus
# knotty sun unfortunately I cannot share more code with you because it is covered by NDA, bu...

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

knotty sun
stuck lotus
# knotty sun Good to hear. Subscriptions for WebGL should not be a big problem, just need an ...

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

knotty sun
#

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

stuck lotus
knotty sun
#

please do

woven veldt
#

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.

knotty sun
#

Native data is unmanaged data so you are responsible for disposing of it, not doing so will result in memory leaks

quartz folio
elder zenith
#

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.

lyric moon
#

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

lyric moon
knotty sun
#

to all you people who insist in posting screenshots of code, the least you can do is INCLUDE THE BLOODY LINE NUMBERS

somber nacelle
#

just hit them with the !screenshots command

#

!screenshots

tawny elkBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

knotty sun
#

they just ignore it

lyric moon
swift cobalt
#

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");

}```
knotty sun
#

I would guess an exception is being thrown

mellow sigil
#

Either the coroutine isn't started correctly, or the object that started it is destroyed during the one second it pauses

swift cobalt
knotty sun
#

debug it

swift cobalt
#

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

sacred plaza
#

And the MonoBehavior the coroutine is associated with isn't modified in any way? Disabled or such?

swift cobalt
#

No

mellow sigil
#

Show full code

swift cobalt
#

this might be the issue

#

I sorted it out. Thank you all for your valuable feedback @mellow sigil @sacred plaza @knotty sun

bitter saffron
#

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

knotty sun
bitter saffron
#

Guess I need a file browser or some sort

knotty sun
crisp scarab
#

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);
sacred plaza
#

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.

fervent furnace
#

why your array can have "empty space"

#

btw i think you will get "duplicate key exception" (i forgot the name) if you use dictionary

knotty sun
crisp scarab
knotty sun
#

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

west lotus
#

Thats far from optimal imho. Depends on how many walls he has

knotty sun
#

the ammout of processing is identical if not less

crisp scarab