#archived-code-general

1 messages · Page 162 of 1

pearl snow
#

Don't wanna upset the compiler

heady iris
#

nah, it's good when it yells at you

pearl snow
#

haha

heady iris
#

that's what it's there for

pearl snow
#

I am joking

heady iris
#

although it can be very confusing to see that error

pearl snow
#

alright let me try that out

steel finch
#

I'm trying to create a melee system for my topdown 2d game , but the common way of just creating an overlap circle doesn't feel right cause it just checks for 1 frame ,not the whole duration ,I have an idea but I want to hear from others too

leaden ice
heady iris
#

you check for the whole duration by checking every frame!

steel finch
#

that was my idea but how do I make the enemy not get hit a million times

leaden ice
#

You can track which colliders you already hit during the current attack and ignore them in subsequent calls

steel finch
leaden ice
#

that too yes

heady iris
#

(even though I use collision events)

#

works the same for both collision events and overlap queries

steel finch
#

I feel smart when my methods work even if they barely do 💀

past gyro
#

Hi i am trying to make my cinemachine camera follow an instantiated prefab but i keep getting this error

#

This is the code

#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;

public class PlayerFollow : MonoBehaviour
{

public GameObject Player;
public Transform FollowTarget;
private CinemachineVirtualCamera vcam;

void Start()
{
    var vcam = GetComponent<CinemachineVirtualCamera>();
}

void Update()
{
    if (Player == null)
    {
        Player = GameObject.FindWithTag("Player");
    }
    FollowTarget = Player.transform;
    Debug.Log($"target = {FollowTarget}");
    vcam.LookAt = FollowTarget;
    vcam.Follow = FollowTarget;
}

}

twilit wedge
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

twilit wedge
#

the way i fixed it was attaching a camera to a prefab

#

so the prefab contained both the prefab and the camera

simple egret
#

Error states that the issue happens on line 26.

leaden ice
#

get rid of var there

leaden ice
past gyro
twilit wedge
surreal valve
#

NavMesh won't be created even though I have everything turned on in Gizmos and have set all of the ground to the Walkable layer

leaden ice
#

i don't use navmesh so im guessing

surreal valve
leaden ice
#

where's the navmesh surface?

surreal valve
#

not in this version

surreal valve
#

2020.3.20f1, personal license running on DirectX 11

leaden ice
#

what version of the ai navigation package

potent sleet
surreal valve
#

Now the ground doesn't load ingame???

#

it still exists in the scene

potent sleet
#

These cutoff screenshots aren’t helpful

potent sleet
surreal valve
#

yes

potent sleet
surreal valve
potent sleet
#

The game object layer here is inconsequential

#

The important part is it’s marked as navigation static and it’s as Walkable navsurface mask inside the object tab of navigation which seems to be set

surreal valve
#

hmm

potent sleet
surreal valve
celest moss
#

is there a way to tile trajectory line sprite along its local y axis

vocal root
#

if i have a list with different gameobjects, and I want to activate a random number of them but checking the index so im not activating the same object its recommended to use a "while" ?

#

Like this for example

randomIndex = Random.Range(0, src_implantes.Count);
                    prevrandom = randomIndex;
                    src_implantes[randomIndex].SetActive(true);
                    sol_implantes[randomIndex].SetActive(true);
                    src_Itemhardware[randomIndex].SetActive(true);
                    sol_Itemhardware[randomIndex].SetActive(true);

                    randomIndex = Random.Range(0, src_implantes.Count);
                while (randomIndex == prevrandom)
                {
                    randomIndex = Random.Range(0, src_implantes.Count);
                }

                    src_implantes[randomIndex].SetActive(true);
                    sol_implantes[randomIndex].SetActive(true);
                    src_Itemhardware[randomIndex].SetActive(true);
                    sol_Itemhardware[randomIndex].SetActive(true);
potent sleet
#

The green edges

whole gull
leaden ice
vocal root
#

Hmm yeah random sorting is a good one

#

thanks

surreal valve
whole gull
#

I have a first person shooter, and I want to display a "threat indicator" on the screen for enemies that are close to the player, but not visible (behind the player). I have no clue how to start, can someone give me a tip how to get started? (I'll figure it out as I go)
this type of threat indicator is often seen in space shooters like freelancer or elite dangerous

#

Actually I just figured it out I think... physics.sphereoverlap or whatever the function is called, get the distance and direction and then draw it on the UI with a normalized distance from the middle of the screen

simple egret
#

How would that indicator look like, visually?
Kind of like the damage indicators in most FPS games, where there's an arrow that rotates around the center of the screen to show where it came from?

whole gull
#

exactly

simple egret
#

Yeah so just like you said. The difficult part is just translating the direction (in 3D) to your screen (in 2D, and rotated to face the screen)

potent sleet
surreal valve
potent sleet
#

Why

surreal valve
#

let me make it all over again

simple egret
# whole gull exactly

Nothing vector math can't solve, probably with a ProjectOnPlane to flatten the direction down relative to your ship's orientation

potent sleet
surreal valve
potent sleet
#

@surreal valve Make a thread so we don’t flood chat

surreal valve
vague token
#

why is my Map like this

#

right screen

potent sleet
simple egret
#

Probably not because of your code

vague token
#

ok sorry

scenic hinge
#

Can someone explain in simple terms what Vector3.ProjectOnPlane does? Shouldn’t it return a plane object or something?

robust dome
#

the heck is that? never heard of it

simple egret
#

It "flattens" a vector on the plane that has a specific normal
Vector3 Vector3.ProjectOnPlane(vector, normal)

#

Red original, blue projected, normal not visible here, but should be vertical

robust dome
#

what is the use case for this

#

any example?

leaden ice
#

that's a super common example

simple egret
#

Appplying force regardless of vertical rotation

#

Or parallel to the ground

leaden ice
#

wall running

robust dome
#

makes sense

simple egret
#

Like, on a slope

leaden ice
#

lots and lots and lots of uses

spring creek
simple egret
#

It's a vector that would be parallel to that line yes, but pointing up

spring creek
#

Ok, thanks, that makes sense

simple egret
#

(the dotted line is not a vector per se in this image)

spring creek
surreal valve
#

My character always floats slightly above the ground, it's always elevated by 0.41 for some reason

lean sail
robust dome
#

check the bounds of your collider

surreal valve
#

alr

heady iris
#

yeah, two options

#

one: your character controller is too tall

#

two: your animations are pushing you a little above your rest pose

#

so it looks good before the game starts, then floats upwards a bit

scenic hinge
#

And thank you

simple egret
#

Yeah that's one of the numerous use cases of that method

scenic hinge
simple egret
#

Depends, in your case and in the image yes

surreal valve
heady iris
#

iirc, as long as at least one animation controls something, then the animator will always control that something

scenic hinge
#

Thank you 🙏 the Unity explanation hurt my soul

heady iris
#

e.g. the position

lean sail
surreal valve
native prawn
#

How can you check if a gameobject from my list of child gameobjects collides with another object?

heady iris
scenic hinge
heady iris
#

Can you describe what you're doing?

#

That'll help decide what's best.

leaden ice
simple egret
vocal root
#

in order to use this shuffle function i need to create a script with a static class?

public static void Shuffle<T>(this IList<T> ts)
{
    var count = ts.Count;
    var last = count - 1;
    for (var i = 0; i < last; ++i)
    {
        var r = UnityEngine.Random.Range(i, count);
        var tmp = ts[i];
        ts[i] = ts[r];
        ts[r] = tmp;
    }
}```
native prawn
simple egret
vocal root
#

thanks, im new with the static term

heady iris
#

the component can do something in response to the collision, or tell something else about the event

surreal valve
native prawn
heady iris
#

Right.

native prawn
#

Alright

heady iris
#

If they're still children, you could also put a Rigidbody on the parent. It will then receive all of the collision events from any child colliders.

#

Not sure if that meshes with your design tho

scenic hinge
native prawn
#

That wont work, the parent is just a empty gameobject so it doesn't collide with anything. But thanks for help though

leaden ice
#

you have a direction to look in

#

position vs direciton

scenic hinge
#

Ohhhh that makes a lot of sense!

soft shard
heady iris
#

the type system can't save you there, since positions and directions are both Vector3's

surreal valve
heady iris
#

i have no idea what they do

surreal valve
vocal root
soft shard
leaden ice
#

it's an extension method

#

you can just do myList.Shuffle(); when you have this

#

oh yeah sorry - you need a static class to put the extension method in

vocal root
heady iris
#

do you have pairs of items?

#

if so, you could always make a List<Tuple<Foo, Bar>> and shuffle that up

pure cliff
leaden ice
pure cliff
#

hey its an awesome new feature a lotta folks dont know about :3

leaden ice
#

It's definitely a cute way to swap two values!
(x, y) = (y, x);

#

whichis exactly what you're doing

#

🤦

pure cliff
#

I also am so hype to learn that you can static overload deconstruction, so now I have this static function and its just so slick looking, so much easier to maintain/read some of this stuff:

public static Direction ToDirection(this Vector2Int vector)
{
    return vector switch
    {
        ( < 0, > 0) => Direction.DownLeft,
        ( < 0,   0) => Direction.Left,
        ( < 0, < 0) => Direction.UpLeft,
        (   0, < 0) => Direction.Up,
        ( > 0, < 0) => Direction.UpRight,
        ( > 0,   0) => Direction.Right,
        ( > 0, > 0) => Direction.DownRight,
        (   0, > 0) => Direction.Down,
        _ => throw new ArgumentOutOfRangeException(nameof(vector), vector, null)
    };
}
leaden ice
#

damn two types of people I guess.

#

I always did this conversion with geometry

pure cliff
#

I was trying to figure out if there was a clean way to do it with math

#

but switch statements run like 20x faster no matter what I tried

leaden ice
#

it's probably true

#

that switches are faster

#

but my brain demands the math solution!

#

I always do it like:
Convert the V2 to an angle around the z axis.
Divide it by (360/8)
round to int (or ceil, or floor)

#

that gives you a number 0-7 for which segment it's in.

#

Which can be casted to the enum

#

your way is almost certainly faster

soft shard
# surreal valve Yes

If you disable your first person controller, does the value stay at 0? If the script is on, are you able to manually drag it to 0?

surreal valve
fluid lily
#

So I saw iOS doesn’t allow reflection in applications? If this is true how does Unity run on iOS devices?

leaden ice
thick terrace
#

you can't use code generation, so some generic stuff doesn't work in C# reflection, but generally unity bakes everything when you build with il2cpp

copper blaze
#

is it possible to use the Animation component to make simple sprite animations? I've found this is only possible using the Animator + a controller

fluid lily
#

I guess you could design the systems in that way, though I imagine that breaks a lot of custom reflection?

thick terrace
#

like you can't generate any new types at runtime by putting together generic types with new params

leaden ice
#

it's still using animation clips

fluid lily
thick terrace
#

or use preserve attributes or whatever you prefer

fluid lily
jade phoenix
#

is there any way i can improve the responsivity of an accelerometer?

#
            if (Input.acceleration.x > 0.4f) inputManager.SwitchLane(LaneDirection.Right);
            else if (Input.acceleration.x < -0.4f) inputManager.SwitchLane(LaneDirection.Left);```I'm using this to detect tilting in my mobile game because the gyroscope was too weird
#

but it takes a good second for the game to realize my phone is tilted before it responds

leaden ice
#

gyro is probably more responsive

copper blaze
#

it was working as intended previously when i had fire_animation switched off legacy and part of a controller

jade phoenix
#

is there an easy way to get a cube object with each side as a different color

#

i just need a test material for orientation purposes

primal wind
#

With probuilder either create a cube using it or probuilderize one then change the materal (or vertex color) of each face

late nymph
#

Im getting error CS0111 for all of the methods in a script, and CS0101 for the whole class.

leaden ice
late nymph
#

I've looked and cant find where

leaden ice
#

ctrl/cmd shift f "PlayerScript"

#

in your IDE

late nymph
#

yeah only once

#

where it should be

leaden ice
#

make sure you're searching the whole project

#

it can be anywhere in your assets folder

late nymph
#

This error occured after I tried to fetch a value from PlayerScript into another script

simple egret
#

Make sure you're hitting Shift yes. Without shift, it searches the current file only

leaden ice
#

i mean none of that really matters - you have a duplicate script. Doesn't matter what you're doing in it

late nymph
#

no way bruh it was in assets

#

okay thank you, the error is fixed

#

🙏

simple egret
#

If the global find from your IDE didn't find two, you might need to get it configured

#

!IDE

tawny elkBOT
#
💡 IDE Configuration

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

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

VS Code*
JetBrains Rider
Other/None

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

simple egret
#

An attempt to find stuff in a project that's not loaded won't yield proper results

swift falcon
#

does anyone have a solution to jittery npc movement for navmesh.setDestination? I already have an invokerepeating which calls navmesh.setDestination(player) every half a second and that seemed to fix some of the jitter but there's still some leftover.

pure cliff
#

Aight, this is the part I am trying to figure out an appropriate way to handle, because Im tryin to think in my head the math for it and I am unsure how to approach it:

var roundTime = roundQueue.Max(q => q.Value.Sum(a => a.MinTime));
if (roundTime < Constants.MinRoundTime)
{
   roundTime = Constants.MinRoundTime;
}
foreach (var (id, entityQueue) in roundQueue)
{
    

}

For all intents and purposes, roundTime is a float in seconds for how long the round needs to be, and roundQueue is a list of floats of min times for a given entity.

I need to normalize the times up such that the sum of the actions is equal to roundTime, but all of them must be greater than or equal to their original times

leaden ice
swift falcon
#

invokerepeating to set the destination is not strange its so its not updating every frame or fixedupdate time

leaden ice
#

now you can multuply all the times by scale to scale them up

leaden ice
#

indeed

#

so you'd want to check for that as well 😆

pure cliff
#

yeh, Im trying to puzzle that one atm, like what does that actually mean

leaden ice
#

I guess it's like... the round takes 10 seconds. If there's 2 actions in the queue that normally take 1 second each, you want to scale them up to 5 seconds each

pure cliff
#

nah cause scale wont work if they have a time of zero total, they instead need to be hard set up to the value but it could be a list so I need to evenly divide

leaden ice
#

but if they already add up to more than 10 it;'s unclear what they want

pure cliff
#

but if I have

0, 0, 0

and the round is 6s, then they need to become

2, 2, 2
#

but 0 * anything is 0 D:

leaden ice
#

seems like a degenerate case

pure cliff
#

yeah but actually a very common one

leaden ice
#

I'm assuming the times are all > 0

#

what if they're negative too

pure cliff
#

nah lots of the actions have no minimum time on em

leaden ice
#

oh sorry I actually - didn't realize you're the OP here lol

pure cliff
#

the min time means "This is the slowest this can go allowable" but some of them are totally fine with being a zero frame "instant" action (IE idling)

#

I could I guess instead have "zero" actually be 0.01f or something very smol

leaden ice
#

yeah for the purposes of this calculation you should give them some token small duration

pure cliff
#

yeah that works I think, shouldnt impact performance and keeps this logic easy to maintain

#

Ill just add a manual >0 check in the struct for sanity to make sure I dont forget in the future

#

@leaden ice I have a big chunk of my logic

#

... lol enter button, derp, sec

#

I have a big chunk of my logic I think I wanna break out a sub service, this one class is getting a bit too big.

The parent service is currently RoundsProcessService and its job is to do the whole "Given n player actions queued, process and start a coroutine for all entities actions for the next n rounds"

The logic is atm as such, all in 1 class (in terms of nesting, so 2 is inside of 1 etc):

  1. Process all the actions for all entities for all the rounds
  2. Process all the actions for all the entities for 1 round n
  3. Process all the actions for all the entities for 1 round, but differentiating between Pre/Post round (to handle that entities can have "haste" and move before the others do)
  4. Process the actions for 1 individual entity for 1 pre/post round

I have all this in 1 monolithic class atm and wanna break it down a bit cuz its getting unweildy... but struggling to think of like... what would I name these modules as I go down A- > B -> C

#

I feel like its 3 layers I can go with?

  1. All of the rounds for all entities and start coroutine
  2. All the entities but 1 round
  3. The actions of 1 entity for 1 round
elfin tree
#

I've been playing around with this volumetric fog thing from github: https://github.com/SiiMeR/unity-volumetric-fog

It's been working pretty well in play mode for quite a while now but it stops working once I make a build, without errors.

Any suggestions on how I could approach this problem?

partially solved

hidden compass
lean sail
# hidden compass https://gist.github.com/SpawnCampGames/c633aa243404f482ece4e63b3ea3b007 hello, I...

how do you plan to populate _saveData here?
I think you'll quickly run into an issue here, where you are saving to one file only which will overwrite all data. This means that all the data you want to save has to be loaded or attempted to be found, or you'll lose some.
Ex: You want to save the position of every npc, lets just assume some destroy for whatever reason but can respawn. (Ik in reality you dont have to destroy them). You may run into issues that npcs arent in the game, so you either load the save data and modify each field specifically, or overwrite the file and lose data about some npcs. This example becomes quite apparent when you try to save other things, like npc location and idk some user settings. What if the npcs arent loaded while the user is changing settings

surreal valve
#

I imported an old asset pack and it broke my previously fine project. What do I do?

hidden compass
# lean sail how do you plan to populate _saveData here? I think you'll quickly run into an ...

wel, so far i only have the player transform to deal with

public class SaveData{
    public PlayerTransform PlayerTransform = new PlayerTransform 
    { 
      pos = Vector3.zero,
      scale = Vector3.one,
      rotation = Quaternion.identity
    };

    public bool FirstTimeLaunch = false;
}

[System.Serializable]
public struct PlayerTransform{
    public Vector3 pos;
    public Vector3 scale;
    public Quaternion rotation;
}
#

ofc these all get created when i initialize the save data which is the FetchSaveData() function in the save manager..

#

which was called 'InitializeSaveData' first..

#

😅 just soo much going on, and the naming had me confused for a while.. when i went back to try to use it

hidden compass
#

bawsi, atm im just going to do players positions and probably a checkpoint index

#
    private void Awake() {
        if (Instance != null && Instance != this) {
            Debug.LogError("GameManager Instance already exists, destroying this object");
            Destroy(this.gameObject);
        } else {
            Instance = this;
        }

        // this part bugs me... why would i be saving and creating a save file every single scene load?
        // Event Fires When Any Scene Loads
        SceneManager.sceneLoaded += HandleSceneLoad;
    }

    private void HandleSceneLoad(Scene scene, LoadSceneMode mode) {
        InitializeScene();
    }

    private void InitializeScene() {
        // should always be called first
        // why? should this always be called first
        this.SaveManager.FetchSaveData();

        GrabReferences();
        //we'll call this to grab each new inventory manager
        //player health //or anything else we need to save
    }

this is my gamemanager script and the only place i access the SaveManager (for now)

#

someone tutored me while making it.. and they made it more robust than i think my use-case will be

lean sail
#

some suggestions

  1. Make the save manager a singleton, just to ensure theres no shenanigans going on with 2 instances ever. Id maybe go as far as throwing an error if 2 exist
  2. implement some interface so you can have different types of save data, and each save data just returns an object of what to actually store.
    https://gdl.space/talutihara.cs this is what i use, its kinda iffy since I have to implement ToSaveable and SaveData but I just dont care to rewrite it at the moment. Each class that wants to save anything just implements the ISaveable interface and handles what the object actually contains. Since this logic is inside the class you want, you already know what the types are
  3. save to different files for different data to avoid the case of loading ALL data previously written just so you can adjust 1 field
hidden compass
#

oh nice, thanks for the insight, i'll look into all this

lean sail
#

in the interface u can see i define a key, thats how i separate the data into new files

hidden compass
#

i was wondering how i was going to do that.. tbh

lean sail
#

u can customize the key in each class which implements the interface, but i like it when the key is the same as the file name

hidden compass
#

b/c im working on my main menu..

#

so the first thing imma run into is the Game Settings..

#

someone mentioned i should seperate these out from the actual gameplay data.. like player position, checkpoint etc..

#

and it sounds ur suggesting the same

lean sail
#

yea u dont really need to have 1 file, id say the only benefit was if you wanted to make some load system where players can save multiple versions

#

then load whatever one they want, which you really only see in a few big AAA games

hidden compass
#

ya, i thought about slots but i finally decided against that for now until i learn more.

#

so for now i was going to either u continue off where u left or u start a new game / new save

#

so we have settings -> and then Play -> using those settings in a new save file

#

if u go back to main menu, it'll populate the settings screen w/ the settings u have modified.. or default if u havent

lean sail
#

OH i remember why i wrote my interface to have both a ToSaveable and SaveData, it was because I can call SaveData() on the class itself, which right now just calls saveManager.Save(this); Otherwise id have to pass in the object to save and the key.
With my current implementation I just send the instance to the save manager so it can directly get the key by itself

lean sail
hidden compass
#

i think im on the right path, its just all the names im using are soo similar i get confused

#

but i think making the save manager a singleton will help alot

#

atm, the gamemanager references it and the gamemanager is a singleton.. but by having it be its own singleton i can directly call my save function from it and not have to worry about going thru the game manage.r.

#

thats a start atleast 😅

lean sail
#

yea the singleton really is just so you can get the reference without any weird inspector serialization or jumping through hoops

#

but it also makes sense to be one so double win

hidden compass
#

mmhmm, well u gave me some stuff to think about, thnks, still gnna try to name some things better.. and write out some better summaries and stuff

#

but i already feel a bit better about it ;D lol

lean sail
#

lol ill be honest i rarely write good summaries, i was just looking through some code where i actually commented what most variables were for and it felt like i didnt write any of this

#

who snuck into my repository and wrote these comments?!

hidden compass
#

me neither.. but im glad i use em for this atleast

wary coyote
#

How difficult is to weld vertexes of different meshes together in Unity? As an automated editor before being built thing?
I am working on a lego-like brick system and am realizing it will be much easier to scope if I could leave holes in the meshes where I could generate the variants of various combinations, but I have never attempted to create a new mesh like that before

#

Things I imagine I will have to account for are the smoothing groups / normals / surface info making sure there's no obvious seams in the mesh?

bright heron
#

why does this code shoot correctly at the mouse position but for some reason when i turn to the right it shoots back at the camera. https://gdl.space/orutixinof.cs

#

Any help would be appriciated

grand gale
#

say i have this navmesh. the red capsule is the AI, and the blue capsule is the player (target).
If i try to pathfind from the AI to the target, it won't give me a partial or invalid path. no. it decides that going at the edge is perfectly fine and exactly what i asked for, and gives me a pathcompleted status. is there any way to stop that? I've been checking every function and forum and i can't really find a way? my only way right now is to ask here, or make my own pathfinding.
also, the agent doesn't have a jump height or anything like that, that would allow for it to cross the gap. there is also no link

hidden compass
torn eagle
#

Might be a bit of a stupid question but is there any way to only set public variables in the class script itself and stop them from having them be set in the inspector for every script of the same class

hidden compass
#

u can assign public variables with code.. just as you would private variables..

torn eagle
#

Yeah I know but some I want dragged in

hidden compass
#

well drag those in

#

if ur saying u want the scripts to run the same whether uve assigned them or not

#

u can always wrap ur functions in conditionals checking if the variable is null

torn eagle
#

Ah ok

#

Thought there may be an easier way to only have some things show in the inspector of derivative classes but guess I'll just do that

grand gale
hidden compass
#
    public GameObject myVariable;

    // Add other public variables here as needed.

    private void Start()
    {
        // Check if the variable is assigned.
        if (myVariable != null)
        {
            // Use the variable for something.
            // For example, let's print its name:
            Debug.Log("myVariable is assigned. Name: " + myVariable.name);
        }
    }```
#

then the code could still work on something that doesnt have myVariable for example

hidden compass
grand gale
#

yep, as i said, it will take the nearest position that it can get, which is on the edge of that opening

#

and therefore it's a valid path

#

rather than actually using the destination i wish for it to use

hidden compass
#

hmm.. does stopping distance of the agent matter any?

#

it might be so high that its a valid location

#

close enuff

grand gale
#

it's 1, and that distance is at least 5 meters. i did consider this anyways though, and made it as far as away as i could

#

and still worked

hidden compass
#

ahh, just trying to brainstorm with u

#

as i dont know why that would happen tbh

grand gale
#

unity is smart pants and re-selects the destination to be the closest one

#

found forums with the same issue as mine

#

but not really any fix

#

atp i might just make my own navigation system

hidden compass
#

fun fact: if u open the navigation panel and select ur agent.. u can see gizmos of its pathing and stuff in the editor

#

may be helpful while ur debuggin this issue

hidden compass
grand gale
#

welp again, it's not much that i can do? the only way i can fix this is by checking if the destination is reachable through custom ways

hidden compass
#

very strange occurance ur having

#

when i get a free minute ill set up a test scene and see if i can replicate it

grand gale
#

i can't find much documentation on how to generate one

#

or i mean there is, but it's hard to follow

#

so it's gonna take a while

hidden compass
#

oh yea i see something about Partial pathfinding

somber nacelle
hidden compass
#

says u cant turn it off but u can write scripting to handle it

#

so perhaps u can find a solution w/o having to write ur own pathfinding

grand gale
# hidden compass

it's a thing, yes. it returns a pathstatus of "partial" if that happens

#

problem: this doesn't happen in this case

#

it genuinely returns pathcomplete

surreal valve
#

Unity says that the object reference isn't to an instance of an object on Line 56 (I did add the animator to the object)

hidden compass
#

ya, i cant say as to why that happens.. i would totally assume it would return partial

grand gale
#

i did too 😭 but i guess not

hidden compass
#

and im pretty sure ur Destination is accurate?

grand gale
#

yep

somber nacelle
#

also your !IDE looks unconfigured

tawny elkBOT
#
💡 IDE Configuration

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

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

VS Code*
JetBrains Rider
Other/None

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

hidden compass
#

i dont think it is.. Monobehaviour is Blue

#

ohh nvm it isnt

#

it supposed to be green

somber nacelle
#

yeah it seems they are using a vs code theme

hidden compass
#

yup

#

it should be the same color as ur Class name

somber nacelle
#

i only realized because Random, Vector3, and Time were all white in the last few lines

hidden compass
#

i wish it would return meta data with the screen grab 😉

#

letting all know its not config'd lol

hidden compass
# grand gale yep

booting up my navmesh example atm.. i'll ping again if i can find a solution

grand gale
hidden compass
#

yea

grand gale
#

what the hell is wrong with my bot then

#

can you show me your code?

hidden compass
#
using UnityEngine;
using UnityEngine.AI;
//SpawnCampGames.com

public class NavMeshDestination : MonoBehaviour
{

    public NavMeshAgent agent;
    public Transform playersTransform;


    public void Update()
    {
        if(Input.GetKeyDown(KeyCode.Return))
        {
            // Check if the destination is reachable before setting it.
            NavMeshPath path = new NavMeshPath();
            if(agent.CalculatePath(playersTransform.position,path) && path.status == NavMeshPathStatus.PathComplete)
            {
                // The destination is reachable, set it as the agent's destination.
                agent.SetDestination(playersTransform.position);
                Debug.Log("Destination is valid and can be reached!");

            }
            else
            {
                // The destination is not reachable; do not move the agent.
                Debug.LogWarning("Destination is not reachable!");
            }
        }
    }

}
#

yup u can use it if u like

grand gale
hidden compass
#

they're two different static planes

grand gale
#

no i mean like

#

the first plane has the navmesh surface component right?

#

when you bake it, does it bake the second plane too?

hidden compass
#

yea

grand gale
#

oh okay

hidden compass
#

bakes em both together

#

i just use the Static tick box on the gameobject

grand gale
#

oh it's not that, it does the same for me too, it was more like

#

"maybe yours arent the same navmesh"

#

and thats why it works for you and not for me

#

but seems thats not the case

#

okay well

#

that seems to work for some reason?

#

thank you

hidden compass
last peak
#

hey guys, im having trouble understanding how to pick a random enum, anyone got a min to help me'?

somber nacelle
#

get list/array of enums, generate number from 0 to collection length, access collection using that generated number as index. it's that easy

last peak
#

this is the part im having a hard time understanding "access collection using that generated number as index"

#

i think im just confused on the syntax

somber nacelle
#

enumArray[randomNumber]
have you never used an array before?

#

also you probably want to cast the array to the type of your desired enum

last peak
somber nacelle
#

MyEnum[] enumArray = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToArray();
not exactly the prettiest line but since the generic GetValues method doesn't exist until .net 5 we have to cast to the correct type. substitute MyEnum in that code for the actual type of your enum

#

or i guess Array.ConvertAll may even be a bit better here instead of the Cast and ToArray call

last peak
#

and thats gonna give me an aaray of enums right

#

?

#

and i can pick my random number from there

somber nacelle
#

it's going to give you an array of the values of that specific enum type, yes

fathom plank
#

something like this should also work

last peak
#

MyEnum is a variable i pass in from the function asking for the random enum

fathom plank
#

(no need for the last cast in the example)

somber nacelle
somber nacelle
last peak
#

it needs to know which enumtype to return the random enum, bad naming on my part

somber nacelle
#

use a generic method. if you pass the type it makes it significantly harder to return the correct enum type

last peak
#

then how will this know which enumtype to use?

#

im sorry if im being dumb here

fathom plank
#

something like this should work for generic (untested)

somber nacelle
#

yep, exactly what i was typing up

last peak
#

i appricate you trying to help though

fathom plank
last peak
#

how would you call that function?

fathom plank
#

like this, where you pass in the type you'd using to do the substitution

somber nacelle
#

you know you can just post the code directly in discord instead of screenshotting it every time, right?

fathom plank
#

yeah, i just like typing it in an ide 🤷‍♂️

last peak
#

liteshot makes it super easy to just screenshot it lol

fathom plank
#

just use win+shift+s

#

and drag a box where u want to screenshot

#

its on ur clip board and u just ctrl+v

somber nacelle
#

ctrl+c, ctrl+v is easier

pure cliff
somber nacelle
#

not in the version of .net unity uses 😉

pure cliff
#

Oh wait is that a dotnet and not C# one? My bad D=

somber nacelle
#

it's .net 5

fathom plank
# last peak that goes way beyond my comprehension tbh

but yeah the where T : Enum is basically just a constraint that <T> has to be derived from Enum, the constraints are useful since having them allows you to make assumptions for what functions are available to be used with the type, etc.

last peak
fathom plank
# last peak OHHH

like if you wanted to construct a new instance of a generic type type in a function, you'd need to do something like where T : new() which ensures that anything thats passed into it can be allocated to let you do something like new T()

#

error goes away now that we have the constraint

last peak
#

thats super neat the short variable names trip me up alot when trying to learn new thigs

fathom plank
#

yeah, some people make them more specific like in the case its restricted to an enum like the previous example, you might use <TEnum> for like "typeEnum", or whatever

#

you can also have multiple generic types available in the same function/class, like void Example<T1,T2>(T1 firstParam, T2 secondParam)

livid sandal
#

does anyone knows what this error is??

'SBaseStat' is missing the class attribute 'ExtensionOfNativeClass'!

i have tried deleting Library then reimporting all assets this error still persist 😢

[System.Serializable]
public struct SBaseStat
{
    [SerializeField]
    public float health;
    [SerializeField]
    public float speed;
    [SerializeField]
    public float attackPower;
    [SerializeField]
    public float armor;
}```
quartz folio
#

If it was previously a ScriptableObject those need to be deleted

#

It generally happens when something has been a UnityEngine.Object type and added as an object, but isn't any more

mighty yew
#

Hey, i've asked about this before but I just ended up getting more lost and I'm honestly looking for clarity. I'm making a roguelike with an inventory system where every item does it's own (relatively) unique thing. one might give you health, another boosts your attack, another spawns gernades when you hit things, another gives you critical chance etc. etc. Is there a system I should use when doing something like this?

#

My current idea is one parent script with a child script for every item, but having that many scripts seems off to me, especially from an organization standpoint. Is there a better way?

pure cliff
#

I believe I mentioned this before, but some varient of Strategy pattern is very likely what you want

#

It really really depends on how much replication you have of common logic, and how well you can or cannot group these entities into common behaviors that can be Encapsulated

prime sinew
#

they're quite versatile, so I suggest you watch a video on it and see if you can use it

#

Brackeys has a video on them

latent latch
#

There's a specific type of pattern for these which is called meta magic, basically you seperate the controller logic from the effect

pure cliff
#

We would need more info on just how encapsulate...able... these things are to give a good recommendation

mighty yew
pure cliff
#

I really really strongly would suspect though that you likely can very much actually handle most of this logic with a small handful of scripts, with 1 "core" script to handle strategy selection, and a handful of basic strategies that have your logic encapsulated to specific "types" of effects

mighty yew
pure cliff
# mighty yew I remember you mentioning strategy pattern but looking it up I'm not really sure...

You come up with encapsulated conceptual "behaviors" your "things" can have, and they are allowed to have more than 1 of them.

You then make a "strategy" for each of these types, and then a matching interface which provides the information for the respective strategy.

Then you just do a bunch of is a checks for if your thing has a given interface, and if so, pass its necessary data into the requesting strategy to consume that data and do the thing

#

To make it serializable with Unity, Id just apply the interfaces to your monobehavior on your prefab, and then you can just make a prefab for each type of inventory item

#

You alternatively can instead have all the fields, nullable, on a single prefab, and then a flagged enum that will enable/disable the respective fields from being shown/hidden in the inspector

mighty yew
#

I remember this now, I might be overestimating my project but I'm not really sure how well this would apply. My system will be similar to binding of issac, risk of rain, or gunfire reborn (specifically the scrolls). While effects can be similar most will do relatively unique things.

pure cliff
#

Binding of Isacc for example I can think of about... I would say maybe 5 or 6 distinct "strategies" for all the powerups?

mighty yew
#

Seriously? Not doubting you but just curious what your thought process is, can you list them out?

pure cliff
#
  1. Projectile
  2. Follow Along
  3. Stat modifier
  4. Trigger effect

Thats off the top of my head

#

Id prolly make a distinct strategy for each type of trigger tbh, like "OnHitStrategy", "OnKillStrategy", "OnDeathStrategy" etc etc

#

but any effect that simply just modifies your projectiles in Binding of Isaac can just be 1 single strategy, composed of like:

  1. How many
  2. What type of projectile
  3. Projectile Spread
  4. Projectile Speed
#

but those are just parameters

mighty yew
#

ok I actually understand what you mean now this would actually be pretty cool

pure cliff
#

So prolly what I would do is step 1,

  1. Make a MonoBehavior that holds aflagged enum for all the different types of strategies (and define that enum as well) (exposed to inspector), lets call this Behavior, and the MB I would call something like InventoryItem
  2. All the serializable fields each strategy needs, grouped together, and then you can use [ConditionalField(...) to hide/show them if the respective flag is set on the enum from #1
  3. An IInventoryItemBehavior interface or whatever you wanna call it, that has a property getter for the enum value it belongs to, and functions for all the stuff inventory items can do, prolly as like an event or whatever? like OnPickup OnInventory OnEquip OnDrop whatever is needed
  4. A concrete implementation for each Behavior of IInventoryItemBehavior
  5. An ItemBehaviorSelector SO that has the list of all the ItemBehaviors you made in 4 (stored as a Dictionary<BehaviorEnum, IInventoryItemBehavior>, and it takes in an inventory item and iterates over the behaviors and invokes them if the item has that behavior flagged
#

Your code should effectively end up looking like:

// Inside of your ItemBehaviorSelector 

public void DoTheThing(InventoryItem item)
{
    foreach (var flag in item.Flags.GetUniqueFlags())
    {
        Behaviors[flag].DoTheThing(item);
    }
}
#

(I swore C# had a baked in way to do this now but I guess not yet)

mighty yew
#

I hate to bother you but I honestly still have some questions (there are some terms you're using that I'm not entirely familiar with)

#

A little confused about the neccesity of the flagged enum. Wouldn't this be the same as having every interface have its specific variables it needs for the actions?

pure cliff
#

yeah so, this example I am giving is for if you want 1 single monobehavior that just has all the fields you need.

Due to the way unity's serialization works, I think 1 single MB that just has all the fields, but nullable, would be way easier to maintain

#

the interface approach would be likely a little bit more performant, maybe, but it would be much more painful to maintain

mighty yew
#

Why would it be more painful? If I want to implement a new type of item I would just add a new interface and implement, rather than have to go back and change everything? Is there other reasons?

#

Also, What is a "SO" (An ItemBehaviorSelector SO that has)?

#

scriptiable object

#

my fault

pure cliff
#

It 100% boils down to one simple thing:

Do you desire/need the support to have more than 1 behavior on a single item? I would typically just go with yes to be safe

#

cuz it would suck if you limited yourself to 1 per and then suddenly were like "Oh now I need more than 1 on some items aaahhhh"

mighty yew
#

Ok that actually makes a lot of sense

latent latch
#

My code actually is very type anonymous. The only things I check for is targeting, but if I were to use an item, it's the item itself that has the logic for what it does and I just call its method.

pure cliff
mighty yew
pure cliff
#

So lets call these things just plain ole Entities to make em very generic

latent latch
pure cliff
#

Lets say you have ProjectileBehavior which expects a Projectile field to be set on the item... And you could make Projectile field type be... another item

And then you can put an Arrow item on the Projectile field.

And then you perhaps could put the Explodes behavior on Arrow make it an exploding arrow...

See how you can nest stuff :3

latent latch
#

My ability controller here, basically all my triggers and stuff are lists which I don't really care for the exact type, only the interface implementation

#

I can actually merge all the triggers, but for editor simplicity I spread it out a bit

mighty yew
pure cliff
latent latch
#

yeah flagged enum and bitwise operations are huge

pure cliff
#

And then you can only run the logic that matches what flags are set in that enum field is all

#

that way you arent doing a bajillion if checks for "is this set? is that set? are those set?"

#

you can break em down into "behaviors" to sort of "group" those sections up, and you may even have already noticed you are naturally "grouping" your behaviors up there :3

latent latch
#

honestly, it's very hard to do these stuff purely of oop. It's possible but you'd spend more time planning than implementing.

muted helm
#

Debug.Log(string.Format("\n----------\n1: {0} : {1}\n2: {2} : {3}", atm1.pressure, atm1.temperature, atm2.pressure, atm2.temperature)); Logging like this, the console shows it like this:

Why aren't I seeing anything except for the first line?

pure cliff
#

so it just lets you save a bunch of effort on having to do a bajillion "if" checks and instead just iterate over the behavior flags and invoke the matching "strategy" for em

mighty yew
#

What is a property getter? you talk about it in step 3?

latent latch
#

checks are fine, I use flags mostly for modifiers mostly. Does fire damage and speed modifiers affect this ability?

quartz folio
#

or change the settings

muted helm
#

Ah, thank you

pure cliff
#

Basically your interface should have

Behavior Behavior { get; }
#

(Behavior being the enum we talked about)

mighty yew
#

Right, what does this do?

#

lol

quartz folio
#

If something turns into an ongoing conversation with explanations and followups, can a thread be made please?

pure cliff
#

Specifies all classes implementing that interface must have a public property called Behavior of type Behavior with a public getter exposed

mighty yew
#

Right cause the interface doesn't actually do anything it just provides a skeleton

#

ok ok makes sense makes sense

pure cliff
#

as vert said if you got any further questions, make a thread for this and ping me on it :3

mighty yew
#

alright real i've got 1 (or 2) more lmao

copper blaze
#

which is better performance wise for moving an object continuously - using Update() or using coroutines?

lean sail
#

if you have a ton of objects, you can have 1 script manage all X objects. rather than have 1 script per object

latent latch
#

unless you're pumping out a bunch of coroutines it probably doesn't matter

#

i've a buff class and usually running 200+ coroutines an update, but I am looking into changing it all

dusk apex
latent latch
#

yeah it comes down to having the ability to fire and forget, but if it's a larger system I'd totally just bind it to an update loop

dusk apex
#

You could probably have some convoluted queue of delegates or flags and whatnot but it'll likely not be worth the hassle.

white gyro
#

How do I disable a TextMeshProUGUI's renderer? I need to disable the renderer specifically. No modifying of color, font, size, or setting the game object or component to disabled.

somber nacelle
#

why can you not just disable the component?

white gyro
#

because it will trigger OnDisable and OnEnable

prime sinew
#

and what's wrong with that..?

white gyro
#

I dont want to trigger those

somber nacelle
#

why

prime sinew
#

why can't you change the color then

white gyro
#

There are some logic in it that I don't want to trigger.

somber nacelle
#

if you just disable the component then it will only trigger its own OnDisable

white gyro
#

Yes exactly

somber nacelle
#

it's renderer is literally the canvas

prime sinew
#

why cant you change the color

white gyro
#

Not possible in this scenario

prime sinew
#

why not

white gyro
#

or rather

#

not advisable

prime sinew
#

why?

white gyro
#

i will have to walk you through the entire system to explain

prime sinew
#

perhaps put it as a child of an object with a Canvas Group component

#

then change the alpha on that instead

#

that's not directly modifying the TextMeshProUGUI component

#

or give it a Canvas component and disable that

white gyro
#

TMP_Text.renderMode looks promising

quartz folio
#

I can't check, but does it not use a Canvas renderer?

pure cliff
pure cliff
#

Theres one other thing and thats modifying the camera mask potentially

quartz folio
#

Then enabling cull is the answer, no?

white gyro
#

is that enableCulling

white gyro
#

Does that require putting the text in its own canvas?

#

Oh it doesn't

#

Oh yeah that did the trick thanks

shell scarab
#

How in the world do I get shadows to follow the QualitySettings.shadows setting in URP? When researching it I see something about setting the lights to follow the quality setting, but i can't find that option anywhere. I see an actual option on the lights to set the shadows to off / hard / soft, but not following quality settings. Same for shadow cascade, although I think that may need to change that in the URP asset I'm using.

somber nacelle
shell scarab
#

well I figured it has to do with code since I cannot find it anywhere on the actual asset settings, but I'll ask there too if I can't find a response here.

#

oh, also I am setting QualitySettings.shadows at runtime, so I figured maybe that's causing something to break and I need to do something extra?

torn eagle
sly quail
#

Hello, I am building a combo system for my game and I would like to know an efficient method on how to do this. Im trying for the efficiency of a Dictionary look up.

#

So with a dictionary you have a key and a value, say fire element gives water in the dictionary, or just a keyvaluepair for that matter.|
But how would I achieve say a lookup of (fire, water) and have it return (steam) for example or in the context of ints it looks up (1, 2) returns (17), but (1, 3) returns 10.
and if there is no value at say (1, 4) return (0).

regal flame
regal flame
#

should work, there's probably a more elegant solution though

sly quail
#

I kinda did something like that but I didnt love it, I had the object itself contain its combos and if a combo element itself was used contain its components. it works, it for sure works but I feel there is a more elegant solution. Well I know it exists im just too inexperienced to know lol

sly quail
regal flame
sly quail
#

I was using scriptable objects for each element

#

not that it matters it would work about the same anyway

#

can you do keyvaluepairs as a key itself in another keyvalue pair

#

thats kinda cursed im not gonna lie

regal flame
#

i probably would avoid that haha. "Fire, Water" would be different than "Water, Fire" too

sly quail
#

hm your right

regal flame
#

there's prolly a way around that though :p

sly quail
regal flame
#

you'd do (slingTarget - holderPos).normalized not just normalizing the position, or? 🤔

torn eagle
#

This is the code

    public void OnEndDrag(PointerEventData eventData)
    {
        Vector3 slingStuff = gameObject.transform.localPosition * Vector3.Distance(gameObject.transform.position, holder.transform.position) * power;

        objectInSling.transform.parent = null;
        babe.isKinematic = false;
        babe.AddForce(slingStuff, ForceMode.Acceleration);
    }
}```
#

Sorry about the crappy gif quality as well my screen recorder just busted itself lmao

sly quail
#

well this all depends on where the actual empty gameobjects are and if the holder is where the holder actually is

#

one sec

somber nacelle
#

why is the amount of force being added using the localPosition as the direction of force?

sly quail
#

when i said the local position i ment the position of the holder relative to the sling shot top

#

thats my bad

#

holder.transform.InverseTransformPoint(slingshot)

#

.normalized again

sly quail
#

that should give a direction

#

there are other ways to do it its just the first that came to mind

regal flame
#

position shouldn't be multiplied into added force

sly quail
#

oh and its a 2D game, not sure if you should use vector2 not 3

#

i dont make 2d games

somber nacelle
#

direction is just (endPosition - startPosition).normalized
i don't see why you would want to make the code look even more confusing by using inversetransformpoint (which being normalized still wouldn't be the correct direction)

sly quail
#

yeah thats how you do it

somber nacelle
#

well it depends really on which object is which, i don't actually know that. but i would assume it is likely the direction would be backwards

sly quail
#

well if its the position of the slingshot relative to the handle it should be the right direction

somber nacelle
#

it's also just a wasteful call when subtraction is much quicker and doesn't need to call into native code

sly quail
#

yeah

sly quail
#

or the other way around I honestly cant be bothered to think about that lol

somber nacelle
#

don't bother normalizing then multiplying by distance

sly quail
#

good?

somber nacelle
#

endPosition - startPosition is already the direction and distance. normalizing just removes the distance

#

remove the Vector3.Distance call entirely

sly quail
#

ohhh

#

i never thought of it like that

#

i meen yeah it makes sense, should of payed more attention in geometry or whatever

#

trig?

#

I like how this isnt even my problem and we are talking back and forth about it

#

Like brother could have written it down minutes ago

torn eagle
#

I'll give that a try!! Thank you all so much!

steady granite
#

I have an issue with colors in non UI TextMeshPro Text (both have same color in inspector, left is non ui, right is ui tmp showing correct color) any idea?

rare owl
#

Hey I had been wondering something

#

My Case:- I have alot of child objects with the same script attached to each of them. Now only one of the objects can be enabled at a time.
My doubt:- I would like to call a function of the script on button press. Now there would be almost 10 objects with the script attached. So what's more efficient, having no checks and update and just calling the function for every instance of the script on button press even though only one of em would be active, or a simple check for the button under update working in the only script active?

#

Thanks

prime sinew
steady granite
prime sinew
rare owl
rare owl
#

I have seperate holders for different weapons which I enable/disable according to what the player has equipped

#

All of that is well networked but let it be

#

Each weapon holder has this script

#

It's still wip. Each weapon would have it's own configuration and animations in the inspector

steady granite
#

if you disable the gameobject, the script is disabled so no update, so no input detection (if using InputManager)

rare owl
#

Yep

steady granite
#

(btw WIN + SHIFT + S to take a partial screenshot 🙂 )

rare owl
#

So my question is would it be more efficient to include a check in the script itself and play anims if the button is pressed or should I stack all the scripts here instead to prevent unnecessary checks.

rare owl
lean sail
#

You can use it on web even

rare owl
#

Yeah I am sorry lemme login

#

yep i am on pc

rare owl
lean sail
#

And you dont want to throw things in fixed update just for the purpose of running things less often

rare owl
#

Lets say I wanna call this on button press

rare owl
#

Only the one enabled would have its function called when the button will be pressed

#

But what about the ones which are disabled? Would unity exclude them? Would unity still try to call all the functions at once even if only one of the scripts in enabled

#

Would that be an unnecessary overhead in comparison with a simple check every frame in the script instead

lean sail
rare owl
#

Keep in mind I'll have 10+ weapons with the same script

torn eagle
#

Anyone able to look over my clamping code it still let's me make the Z position whatever when I drag

    public void OnDrag(PointerEventData eventData)
    {
        Ray R = m_cam.ScreenPointToRay(Input.mousePosition); // Get the ray from mouse position
        Vector3 PO = transform.position; // Take current position of this draggable object as Plane's Origin
        Vector3 PN = -m_cam.transform.forward; // Take current negative camera's forward as Plane's Normal
        float t = Vector3.Dot(PO - R.origin, PN) / Vector3.Dot(R.direction, PN); // plane vs. line intersection in algebric form. It find t as distance from the camera of the new point in the ray's direction.
        Vector3 P = R.origin + R.direction * t; // Find the new point.

        P.z = Mathf.Clamp(transform.position.z, -0.019f, -0.1f);
        if (P.z <= -0.1f || P.z > -0.019f)
        {
            transform.position = P;
        }
    }   ```
dusk apex
#

Log the z value before and after change

#

If the after value is correct, elsewhere has got the value changing.

torn eagle
#

Wait what do you mean sorry

#

I'm not sure how and where to declare it

#

Would I just ran this at the start as well??

P.z = Mathf.Clamp(transform.position.z, -0.019f, -0.1f);
        if (P.z <= -0.1f && P.z > -0.019f)
        {
            transform.position = P;
        }```
#

Turns out I'm an idiot and was using && instead of || but now as soon as my mouse exits the bounds it stops moving entirely

public void OnDrag(PointerEventData eventData)
    {
        Ray R = m_cam.ScreenPointToRay(Input.mousePosition);
        Vector3 PO = transform.position;
        Vector3 PN = -m_cam.transform.forward;
        float t = Vector3.Dot(PO - R.origin, PN) / Vector3.Dot(R.direction, PN);
        Vector3 P = R.origin + R.direction * t;

        P.z = Mathf.Clamp(transform.position.z, -0.019f, -0.1f);
        if (P.z <= -0.1f || P.z > -0.019f)
        {
            transform.position = P;
        }

    }
ashen yoke
knotty sun
jovial moon
#

I'm trying to use OpenFracture on my custom mesh, but nothing happens. Any idea where to begin debugging?

uneven monolith
#

okay this is annoying af, Im like 99% sure i set a variable to right value, and it shows in both debugs and in Visual studio debug window at right value, but then when i use that variable couple frames later in different method, its reseted

uneven monolith
#

like only explinations i can think are:
-it doesnt save it for some reason
-it saves it at wrong object/i have some clone object fake shenanigans going on
-idk, other wierd bs

uneven monolith
#

idk is this anything i can get help with because its so messed up:D

static matrix
#

ah so interfaces are very similar to abstract classes

#

pros: you can implement multiple on one object
cons: You can only have methods and not vars it looks like

static matrix
#

you can?

#

ok I misread that then

uneven monolith
#

yeah

static matrix
#

oh properties but not fields/vars

#

hmm

steady moat
#

Interface cannot implement.

#

They expose a "contact"

static matrix
#

interface can be implemented

#

a class can implement multiple interfaces

steady moat
#

The interface itself will not implement something

static matrix
#

yeah

steady moat
#

This is what I was saying

static matrix
#

yeah, i misspoke ig

steady moat
#

However, in newer C# version. You have:

simple ridge
#

Hi everyone, just a quick question but is it possible / easy (as this is only a minor thing) to render handles on top of gizmos? Right now I have a handle label, and its rendering behind some Gizmos.DrawLines just wondering if I can reverse the order?

uneven monolith
# rigid island post relevant scripts

figured it out, My other code referenced a prefab, other referenced instation of it, but code was so messy i couldnt figure it out(and i doubt anyone here would have), but thx for offering a help

#

i hate programming sometimes

#

i spent like 4 hours of procastination on that bug

rigid island
uneven monolith
#

yeah propably :D

jade phoenix
#

i have a string like this "10010" and i do this to it:

            List<int> bar = level.levelData[progress]
                .Split()
                .Select(str => int.Parse(str))
                .ToList();```and for some reason, it returns with a size 1, as the same 10010 but this time as an int
#

how do i get it to split correctly into individual chars

jade phoenix
#

but i want my result to be [1, 0, 0, 1, 0]

leaden ice
#

yes

#

get rid of the Split()

thin aurora
jade phoenix
#

thats exactly the point

thin aurora
#

Otherwise it will enumerate the single array entry Split returns

#

It's not splitting your string

leaden ice
#

Your split is literally just giving you back the same string as one entry in an array

thin aurora
#

So what PraetorBlue said, remove Split

leaden ice
#

Just remove Split and it will work

jade phoenix
#

that doesnt make a lot of sense

#

all it's gonna do is return [10010]

leaden ice
thin aurora
#

A string is an array of characters

leaden ice
#

so when you do Select on it

#

it will do each char

thin aurora
#

So Select will enumerate the characters

leaden ice
#

make my day

thin aurora
#

(it's not actually an array of characters but it will be converted to one by c#)

jade phoenix
#

does int.Parse not take chars?

thin aurora
#

Ok this is a bit dumb because it indeed doesn't

leaden ice
thin aurora
#

You can probably get rid of the ToString stuff someway but this works

#

Top one is the current one, bottom is the suggested fix

leaden ice
thin aurora
#

Thanks for creating the exact same fiddle lol

leaden ice
#

oh lol

jade phoenix
#

flittle my dittle

leaden ice
#

didn't even see

thin aurora
#

Anyway, ToArray and ToCharArray basically does the splitting you want

leaden ice
#

becauase I was too busy working on my fiddle lmao

jade phoenix
#

its just weird that it does it for you

#

seems like something i'd rather have control of

leaden ice
#

the ToArray isn't needed though

thin aurora
#

Because a string is not actually an array of characters

#

Oh works too

leaden ice
#

you're using Linq (Select is from Linq)

#

Linq works on IEnumerables

#

string is IEnumerable<char>

#

so when you call Select on a string, it operates on each char

jade phoenix
#

im used to java lambda functions

leaden ice
#

works the same way

jade phoenix
#

yeah but i think you have to specify split in java

thin aurora
#

I want to make a point but that class is so goddamn big

#

Individual characters are fetched internally

leaden ice
jade phoenix
#

hm interesting

thin aurora
#

So there's no "array of characters" here. It's a string that will have its characters in memory fetched when you want an array of characters

jade phoenix
#

alright so the data splitting works now

leaden ice
# jade phoenix hm interesting

OK that was not quite right it's been years since I did Java

Stream<Character> characterStream = testString.chars()
  .mapToObj(c -> (char) c);```
jade phoenix
#

yeah the chars()

leaden ice
#

that just gets the character array though

#

because Java doesn't have the fancy IEnumerable interface shenanigans

jade phoenix
#

does the same thing as a split and has to be explicitly stated

leaden ice
#

it's not a "Split" call

jade phoenix
#

minus the to string

leaden ice
#

chars gives you just an array of chars which is the whole string

#

but your confusion was that:
"1001".Split() actually gives you ["1001"] not ['1', '0', '0', '1']

swift aspen
#

The reason why you got a while string out is that .Split() operates on whitespace if you don't specify the delimiter, but your string had none

jade phoenix
#

i really only use split when im doing code competitions

#

ig i got it confused with python

orchid bane
#

Is IDragHandler deprecated or something? Can't find it in the newer scripting references

orchid bane
#

Could you give me a link to it?

rigid island
#

@orchid bane if you just type IDragHandler it should give you the suggestion in VS no ?

orchid bane
#

It does but I wanted online docs

jade phoenix
#
    void Update()
    {
        timer += Time.deltaTime;

        // Spawn one note per BPM if you haven't run out of bars.
        if (timer >= ((level.bpm / 60) / 60) && progress < level.levelData.Count)
        {
            // Bars are saved in json as 6 char long strings.
            List<int> bar = level.levelData[progress]
                .Select(c => int.Parse(c.ToString()))
                .ToList();

            // Spawn a note at a spawner if pos within bar == 1.
            for (int i = 0; i < bar.Count; i++)
            {
                if (bar[i] == 1) Spawn(spawners[i]);
            }
            timer = 0f;
            progress++;
        }

        // To restart the level.
        if (keyboard.spaceKey.isPressed) progress = 0;
    }```whenever i run it for the first time, it's able to spawn the notes with the correct bpm spacing apart, but whenever i restart the progress, every bar in the config gets instantly spawned.
leaden ice
#

well you're just looping over them all and spawning

jade phoenix
#

a bar is just one row of notes

leaden ice
#

no time delays in here

jade phoenix
#

but it's spawning all the bars at once

leaden ice
#

right

shell pasture
#

Hey guys, how to await a task in a coroutine, while also getting the value

leaden ice
#

you're looping over them

#

and spawning them

#

there's no time delay

rigid island
#

whats point of Coroutine then

jade phoenix
leaden ice
leaden ice
#

everything will happen instantly

jade phoenix
#

?

#

this is the config for reference

#

every frame, it's only supposed to get the bar from whatever progress is

swift aspen
jade phoenix
#

thats to calculate bpm

#

ik its messy but it works

swift aspen
#

no its literally = 0

#

its integer math 180 / 60 = 3, 3 / 60 = 0.05 (cast as int) = 0

jade phoenix
#

0.05

leaden ice
#

assuming bpm is a float it'll work

#

if it's int, it'll be 0

swift aspen
#

do 60f instead of 60

#

see if it fixes it

spiral ibex
#

@jade phoenix since you never reset the timer, when you reset the progress it probably spawns all the notes at once?

jade phoenix
#

i do reset the timer

spiral ibex
#

ah apologies

#

you reset it after spawning, but not when resetting the progress

jade phoenix
#

yeah i thought about it and it doesnt make much of a difference

#

the condition still works

spiral ibex
#

It would delay all the notes by one though

#

have you tried setting timer to 0 along with progress?

jade phoenix
#

would you know why the bubbles spawn so closely together?

#

i set the bpm all the way down to 4 and it still seems like they're spawning in pairs

orchid bane
#

We here handle subs and unsubs to event in OnEnable and OnDisable, but how do they handle them in other dev fields?

swift aspen
jade phoenix
#

would i just multiply that result by 60 to represent it in seconds and not minutes though

swift aspen
#

1 minute = 60 seconds

60 seconds / 180 beats per minute = 0.33sec between each beat

spiral ibex
#

e/subscrube/subscribe

orchid bane
orchid bane
spiral ibex
jade phoenix
#
    public void OnTouchPressed(InputAction.CallbackContext context)

        if (context.performed)
        {
            var touchPos = Touchscreen.current.position.ReadValue();

            Ray touchRay = Camera.main.ScreenPointToRay(touchPos);
            RaycastHit touchRayHit;

            if (Physics.Raycast(touchRay, out touchRayHit) && (touchRayHit.transform.CompareTag("Bubble") || touchRayHit.transform.CompareTag("Bad Bubble")))
            {
                if (touchRayHit.transform.parent.parent.GetSiblingIndex() == currentRunwayInd && Physics.Raycast(touchRayHit.point, -touchRayHit.transform.up, clickSpaceLayer))
                {
                    Destroy(touchRayHit.transform.gameObject);
                    Debug.Log(betterTimer);
                }
            }
        }
    }```how can i change this so it can detect whenever multiple fingers tap down in different places at the same time?
regal flame
#

iirc there is an Input.touches list~~, gotta doublecheck~~ there was! you can probably use that 🙂

jade phoenix
#

got it working thanks

#

it was surprisingly easy as well

sharp acorn
#

TMProUGUI.GetRenderedValues is giving me outrageous values

#

This is the hierarchy. I'm trying to get the size of "lesson" in order to resize "LessonModule (Clone)"

#

The only thing I changed from the default implementation of Scroll View from Unity is that I added both a Vertical Layout Group and a Content Size Filter to the "Content" gameobject

robust dome
#

are you trying to reference the transform lesson?

sharp acorn
leaden ice
#

why do you need to call weird functions and get heights

sharp acorn
sharp acorn
leaden ice
swift falcon
#

By sounds of it Rocco wants to scale the nodes depending on the text?

leaden ice
swift falcon
#

You'd still use a verticle layout group on top of it though

leaden ice
#

VerticalLayoutGrou[p and layout elements and content size fitters solve all of this automatically

#

you don't need any code

sharp acorn
leaden ice
#

if you set it up properly

swift falcon
#

I'll take Praetors word on this, I've not had a need to automate with text

leaden ice
sharp acorn
leaden ice
#

you need to read that thread

sharp acorn
#

So I need to make the text the parent object?

#

There is tecnically two texts, one for the title and the other for the text, idk how to go around that

#

I'll read the other thing you sent, see if there is a better solution

swift falcon
#

I am working on a mechanic that allows me to paint walls / objects and etc... I already have the code down for grabbing the correct submesh to get the material where the raycast hits but I need to figure a way to handle allowing the player to pick new materials to paint.

I was thinking of having a struct for each texture which would contains

  1. Texture
  2. Array of "Tags" strings?

Maybe contains all of these into a list? and have their index as an ID that I save on the object? So for instance I might have
wallData.paint[1] = 3;

When I select the object I could get the tags on it for compatibility and then use a filter on the list of textures? But I duno if this is messy

wicked wolf
#

How to make completely dark areas inside objects in an isometric game. Scripts? Shaders?

swift falcon
wicked wolf
sharp acorn
swift falcon
wicked wolf
#

*part of the surface

the rest is camera background

leaden ice
#

raycasts and colliders at the most basic level.
Note that the collider you interact with for your interaction system does NOT need to be the same as the physical collider the object might use in the game world

#

As I already said:

Note that the collider you interact with for your interaction system does NOT need to be the same as the physical collider the object might use in the game world

#

You can use a much larger/simpler shaped collider for this purpose

#

Also

You must need to interact with the origin of the collider
I have no idea what this means

jade phoenix
#
    void Update()
    {
        map.ForEach(c => {

            float h, s, b;
            Color.RGBToHSV(c.Value, out h, out s, out b);

            h += progress;
            progress++;
            if (progress >= 255) progress = 0;

            c.Key.GetComponent<Renderer>().material.color = Color.HSVToRGB(h, s, b);
            //c.Key.GetComponent<Renderer>().material.color = new Color(Random.Range(0, 255), Random.Range(0, 255), Random.Range(0, 255));

        });
    }```would anyone know why changing the hue of a material's color makes it completely black?
tiny pollen
#

i need minimum translation speed

mellow sigil
jade phoenix
#

oh wack

#

is there a way to covert it

swift falcon
#

I think 255 is Color32?

spiral ibex
#

divide to 255?

jade phoenix
#

wait that shouldnt change anything though?

#

cause im only changing hue not rgb

mellow sigil
#

Hue is also from 0 to 1

jade phoenix
#

but isnt hue one of those things that just wraps around if you go over

#

like an angle

#

or am i just crazy

mellow sigil
#

Could be, but the hue values of the HSVToRGB method are from 0 to 1

swift falcon
#

I mean it's from color and none of the colours inherently get the remainder so I'm not sure if hue would act any different

leaden ice
jade phoenix
#

ah fancy

leaden ice
#

unclear what progress is though

jade phoenix
#

its just a thing to allow a rainbow cycle

#

i could probably use something from Time

swift falcon
#

Oh bro... even if it wraps

#

You'll always have a value of 1?

jade phoenix
#

not if its a float

swift falcon
#
progress++;```
leaden ice
#

It's unclear to me why progress would or should change here

swift falcon
#

Even if it's a float, ++ will always add 1 no?

leaden ice
#

yes but that's not what the suggestion was

swift falcon
#

I assume progress starts at 0 and thus adds 1 and ends up 1 and remains one

spiral ibex
#
        float f = H * 6f;
        int num3 = (int) Mathf.Floor(f);
        float num4 = f - (float) num3;

From the IL code it looks like it's always going to be 0 @jade phoenix

jade phoenix
swift falcon
#

@leaden ice They stated they want some rainbow effect but how does adding 1 to a 0-1 value ever change anything when you wrap?

leaden ice
#

I mean maybe they want:

h += Time.deltaTime * speed;
h %= 1;```
jade phoenix
#

because the initial hue != 1 or 0

#

so like .2 + 1 wrapped is .8 or whatever

swift falcon
#

It still makes no sense to add 1 to a 0-1 value

leaden ice
#

indeed, hence the removal of that line in all my code examples

spiral ibex
jade phoenix
leaden ice
swift falcon
#

I think they just want to flip it once like making 0.2 = 0.8 and 0.5 = 0.5?

#

I duno why though

leaden ice
#

wat?

jade phoenix
swift falcon
#

so like .2 + 1 wrapped is .8 or whatever
I'm using the example they provided here

leaden ice
jade phoenix
leaden ice
#

I honestly don't understnd why you're even using a Dictionary here

swift falcon
#

I assume to attach the gameobject to the colour

#

They don't use it though

leaden ice
#

but their code isn't using it

#

it's not syncing the color in the dict to the gameobject at all

swift falcon
#

Yeh I can see

#

I think they are thinking the value is a reference to the objects colour

leaden ice
#

Just do:

List<Renderer> renderers = new();

void Start() {
  foreach (Transform child in transform) {
    Renderer r = child.GetComponent<Renderer>();
    renderers.Add(r);    
  }
}

void Update() {
  foreach (Renderer r in renderers) {
    Color c = r.material.color;
    float h, s, b;
    Color.RGBToHSV(c, out h, out s, out b);
    h += Time.deltaTime * 10f;
    h %= 1;
   
    r.material.color = Color.HSVToRGB(h, s, b);
  }
}```
@jade phoenix
#

your code is overcomplicating it

swift falcon
#

Also try to avoid getting the same component over and over, it's not all that cheap to do

jade phoenix
#

GetComponent isn't cheap?

uneven slate
#

Nope. Cache the result of it.

leaden ice
#

besides isn't it just ugly to have to write it that many times??

shell scarab
#

how do I set all lights to hard/soft shadows at once? I thought QualitySettings.shadows would do it but no.

shell scarab
#

I thought maybe I could use this, but it seems actually most of these properties are read only

shell scarab
leaden ice
#

for readonly properties, it would seem so

shell scarab
#

why are soft/hard shadows not changable? that is so weird to me. How do other games provide graphics settings to their users if half of them seem to be locked?

leaden ice
#

this is more about whether the pipeline itself supports soft shadows

#

I think hard/soft shadows are something that is configured on a per material basis

shell scarab
#

There's QualitySettings.shadows but that doesn't work in URP.

leaden ice
#

or a per light basis

shell scarab
#

hrm

#

well anyway, for QualitySettings.renderPipeline do I need to have a different pipeline asset, or can I load one from Resources and just edit the write values and set the override?

cursive hollow
#

Is it ok if I ask a python question here real quick?

#

Have not used it in a year and every other coding server I’m in is dead

rigid island
#

try The Coding Den

#

last message on python channel is 1:50 pm you should be fine

vale wharf
#

Trying to modify and 'improve' a dungeon generating algorithm to fit my needs.

The algorithm as it currently stands works like this:

  • Place a starting room and add it's exits to a list (pendingExits)

  • For a certain amount of iterations, go through every pending exit and place a new room at them.

  • If the new room doesn't overlap anything, add the new room's exits to the pending exits list (skipping if it finds no room that doesn't overlap anything when placed)

The changes I want to make are:

  • Allow a way I can force there to be only a certain amount of a specific type of room placed(so I can define 'special' rooms which only appear once or twice throughout the generated dungeon)

  • Remove the iteration based generation and replace it with something that guarantees the amount of rooms generated
    How can I modify the algorithm as it currently is to achieve this?

How can I modify the algorithm to include the changes I waant?

cedar jolt
#

Is there a way to call a founction next frame?

leaden ice
cedar jolt
leaden ice
#

a coroutine will let you write code like:

  • wait one frame
  • do something
cedar jolt
leaden ice
#

or just

#

yield return null;

#

note that this only works inside a coroutine

cedar jolt
#

Thank you!

pure cliff
#

like, await Task.FrameDelay(int frames) or whatever

leaden ice
#

no idea

#

I don't use async / await generally

cedar jolt
#

public static class WaitFor
{
    public static IEnumerator Frames(int frameCount)
    {
        while (frameCount > 0)
        {
            frameCount--;
            yield return null;
        }
    }
}

public IEnumerator CoroutineAction()
{
    // do some actions here  
    yield return StartCoroutine(WaitFor.Frames(5)); // wait for 5 frames
    // do some actions after 5 frames
}

marble badger
jade phoenix
#

does anyone know any good resources for mobile haptics? cant really find anything online

thick terrace
#

err

#

Task.Yield()

#

don't use delay!

marble badger
#

if so, your second constraint is quite easy to meet - instead of placing a room for every pendingExit on each iteration, just pick one of them at random. repeat until you've placed numRoomsDesired rooms, then convert all remaining pending exits into dead ends.

If you have to do it by placing extra rooms on each pending exit (i.e. placing an extra room which has no other exits) then you repeat until you've played numRoomsDesired - pendingExits.Count rooms, then place the dead-end room at each pending exit. (In theory you might end up with fewer than numRoomsDesired this way because two pending exits might open onto the same tile).

jade phoenix
#

would anyone know why it's not taking the method like its supposed to

#

it only works when i pass the method as a string

buoyant crane
jade phoenix
#

oh

#

woopsie

rain minnow
#

yep . . .

gray grove
#

Is this code inefficient?
Resharper unity plugin marks it as is, but everywhere I look online i says that transform is cached

leaden ice
#

that's a microoptimization

orchid island
#

what am i doing wrong here?

leaden ice
#

or a deactivated particle system