#archived-code-general

1 messages ยท Page 372 of 1

slim trail
#

force?

hexed pecan
#

Force, velocity or moveposition

#

Probably either one of the first two

slim trail
#

but it works on other objects

hexed pecan
#

Oh it has an animator

slim trail
#

i can delete

hexed pecan
#

Maybe you have an anim clip playing that is modifying the root object's position

slim trail
#

lolll

#

now works

hexed pecan
#

Good, although you should still move it with rigidbody so you get correct physics

slim trail
#

ok

#

i will try it

#

thank you

sonic venture
#

How do I achieve a realistic boxing fight in Unity? Like animations not clipping through the bodies, and I was thinking about animation rigging to stop the hand whentouching the body, but how cna I do that?

wispy depot
#

Is there a built in unity method for referencing other scripts variables by string? Like invoke, but for variables

leaden ice
wispy depot
#

I'll find another way I suppose

leaden ice
#

Learn to use a Dictionary.

#

and enums

wispy depot
#

Perhaps sometime if I need to, but I think I have another way in mind. Either way, the gsame I'm making is incredibly lightweight so it won't have a performance impact.

leaden ice
#

Sounds like you're planning to use something way more complicated ๐Ÿค”

wispy depot
leaden ice
#

As would a dictionary

wispy depot
#

I have given up, I'll learn a dictionary

leaden ice
#

Here's a simple example:

Dictionary<string, float> stats = new();

public void SetStat(string name, float value) {
  stats[name] = value;
}

public void GetStat(string name) {
  if (stats.TryGetValue(name, out float value)) {
    return value;
  }

  return 0;
}```

And to use it:
```cs
myScript.SetStat("hp", 100);
myScript.SetStat("armor", 10);

//... later
float hp = myScript.GetStat("hp"); // gives 100
float armer = myScript.GetStat("armor"); // gives 10```
near crown
#
                Camera.main.ScreenToWorldPoint(Input.mousePosition), DistanceVector,distance:Mathf.Infinity, grappleLayer
            );```
I have this raycast, I wonder how to make it return only the first thing it hits and not the one the mouse touches at its exact location. does anyone know how to do it?
leaden ice
near crown
maiden ingot
#

Does someone know why the raycast isn't drawing?

leaden ice
maiden ingot
rigid island
leaden ice
#

you don't have any code that draws anything

#

If there is something being drawn in the tutorial, it's because they wrote code to do that.

maiden ingot
leaden ice
#

Otherwise, they've written another line of code

#

You need to do one or the other of those two

maiden ingot
#

i see

#

thx

leaden ice
#

Take a look at TABS (Totally Accurate Battle Simulator) for example

sonic venture
#

No I don't want ragdolls and physics that much

#

But in undisputed, idk how they made it

leaden ice
#

Then it's going to be quite hard to achieve "realistic". Real boxing is all physics

sonic venture
#

Or in other fighting games

sonic venture
hexed pecan
#

I'm pretty sure that those UFC/Undisputed games are using some sort of active ragdoll/physics animation

sonic venture
sonic venture
#

I think if I use a single ik constraint I can limit the elbow stretched out no?

#

But for each animation I have to define a limit

hexed pecan
#

I'm not too familiar with Unity's built in IK or any assets, I write my own

sonic venture
#

And what about uppercuts, that can be sketchy

hexed pecan
#

This is going to be tricky to get right

hexed pecan
spare dome
#

TABS is solely based off of active ragdolls

placid edge
#

how do i make an object be able to get clicked on even if there's another object in the way?

cosmic rain
placid edge
#

how would I go about making the object get ignored?

cosmic rain
placid edge
#

well, its just a button, and the object on top just follows the mouse

cosmic rain
#

A UI button?

placid edge
#

yyyes

#

wait are there other kinds of buttons?

cosmic rain
#

Ui(assuming canvas ui), uses the event system and raycasters to detect the pointed objects. The object in front would need the "raycast target" disabled on its graphic component.

placid edge
#

oh i see on image there is a bool for raycast target could I disable that?

#

well well well

placid edge
#

haha

#

thanks dlich

cosmic rain
placid edge
#

oh right

kind osprey
#

I have a question.

I am planning on doing a class select (barbarian, rogue, wizard, fighter) but i have my stats in a singleton like this

myHealth
myArmor
myDamage
myMana

i have some rough idea on the values I'm implementing based on the class selected so i was wondering if there is a better to assign values when choosing a class so i dont have to keep doing if (class == rogue) myStats = rogueStats and so on
is it inheritance, or something else

#

basically i dont want to have to type each specific stats for each specified enum

leaden ice
solemn ember
#

sup gang, I'm having this issue after a power outtage

leaden ice
leaden ice
# solemn ember

Have you made any working project commits or backups recently?

#

presumably your project is corrupted in some way from the power outage

solemn ember
#

just a power outtage

solemn ember
#

it's a pretty new project, haven't done backups yet

leaden ice
#

Then... you may be in a little trouble.

solemn ember
#

commits

leaden ice
#

I would recommend making backups or commits frequently to reduce the risk of losing data to unforseen disasters

leaden ice
# solemn ember

Why are you showing a screenshot of the build profile page

solemn ember
#

it's empty xD and messed up

solemn ember
#

hmm so nothing to do about this?

solemn ember
#

okok ok

#

let's see if I can find that

kind osprey
#

but i did a switch statement

drowsy mauve
#

(wrong channel)

leaden ice
leaden ice
drowsy mauve
#

Alright, I'll delete and move there

#

Thanks!

sudden lantern
#

I make the camera follow the player vertical position smoothly, but I have the problem that in some situations the player goes out of the camera's view. How to clamp these values?

if (actor.stats.isGrounded)
{
    _tempTime = Mathf.Lerp(_tempTime, 0, SurgeMath.Smooth(1 - 0.925f));
}
else if (actor.stats.isInAir)
{
    _tempTime = Mathf.Lerp(_tempTime, yFollowTime, SurgeMath.Smooth(1 - 0.9f));
}
_tempY = Mathf.Lerp(_tempY, target.position.y, SurgeMath.Smooth(1 - _tempTime));
_tempFollowPoint = target.position;
_tempFollowPoint.y = _tempY;
cosmic rain
sudden lantern
#

but how is this related to my question?

cosmic rain
#

It's probably not. Just stands out as it's not a very correct way to Lerp.

#

You can clamp the _tempY to whatever values you want before using it.

sudden lantern
cosmic rain
dusk apex
sudden lantern
solid relic
#

I want to make a drop system that if i hold "Q" it will display an arc where the object is going to land. Something like in the image below. How would i achieve this?

plucky inlet
cosmic rain
solid relic
#

I used a line renderer to get the arc and using: https://www.gamedev.net/forums/topic/512304-good-throwing-arc-equation/
i got the formula and then assigned it to look like this:

void showTrajectory()
{
    int trajectoryPoints = 100;
    Vector3 direction = (Camera.main.transform.forward*5f)+transform.up;
    Vector3 startPos = hand.position;

    Vector3[] points = new Vector3[trajectoryPoints];
    for(int i = 0; i < trajectoryPoints; i++)
    {
        float time = i * 0.01f;
        points[i] = startPos + direction * time + 0.5f * Physics.gravity * time * time;
    }
    lineRenderer.positionCount = points.Length;
    lineRenderer.SetPositions(points);
}

My throwing direction, the start position and then the formula and then setting the positions.
The line renderer though doesn't look the best.. so i'm trying to use a material, how do i make the material more visible? currently my scene is mostly all white because i don't have an artist and i haven't gotten to it yet. Any suggestions?

cosmic rain
#

Assign a texture

#

Maybe both

nimble echo
#

is it normal to have a lot of variables be assigned from the inspector?

#

mainly for the "game manager" script

knotty sun
#

yes, that is generally best practice

nimble echo
#

ohh okay

#

makes sense

cosmic rain
#

Assigning variables in the inspector is a good practice, but assigning too much variables is not.

nimble echo
#

for the game manager there are 10, and for some ui scripts there's like 5 each

solid relic
#

that's not that many.. is it?

nimble echo
#

i thought it was

solid relic
#

That's my player script

nimble echo
#

ohhh

#

fine i think mine's okay actually

solid relic
#

I'm not sure how many dlich might think is a lot

#

i don't think it is no..

somber nacelle
#

that's not unity related at all, so not the right channel nor the right server

white isle
#

why not
its writing speed for coding

#

anyway will delete

somber nacelle
white isle
#

ok
ty

vagrant blade
#

Nobody is going to guess a solution without some explanation on how you've implemented this.

gloomy hornet
#

ok i solved it

sweet verge
#

I have this:

[NonSerialized] public Vector3 velocity
        = new Vector3(0,0,0);

when I do ctrl + s, it formats it to

[NonSerialized]
public Vector3 velocity
        = new Vector3(0,0,0)'

I don't want that. I"m using VSCode and editorconfig. Can I disable this adjustment?

hexed pecan
#

You should see something like this

sweet verge
calm fulcrum
#

Hello
I have an issue with rendering colors of my mesh, I created simple script that create grid and apply uv to each cell based on it's x grid position, but when I start the game the colors on my texture are much darker than on my texture.

#

this is a screenshot of my material

vagrant blade
#

Try making it an unlit material?

tawny mountain
#

I guess this is a good place as any. I need help with saving/loading yo json file. I think it may be the data I'm trying to save but It saves an empty dictionary.

#

I have my script. It's Firebase firestore. But I want a copy of player save data offline

hexed pecan
calm fulcrum
hexed pecan
#

I know ๐Ÿค”

tawny mountain
#

One second gathering materials

thin aurora
#

JsonUtility is very bad when it comes to serializing common types like this. Newtonsoft has a Unity package available and the syntax is almost the same

steady moat
#

!collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โ€ข Collaboration & Jobs

karmic mulch
#

:[

tawny mountain
#

@hexed pecan and @thin aurora
Your saying that if it's my data types (because I do have a timestamp being saved as a generic object for firebase firestore) that json utility may not be serilizing it properly? I can try to use Newtonsoft.

dusky lake
# karmic mulch aah okay its fine

There are some gamedev discords out there that allow you to search for collab partners (Game Dev League, Game Dev Network), I'm sure you can find them through discords server search

dusky lake
thin aurora
karmic mulch
thin aurora
#

So in short, it's not a good tool in the slightest. The only thing it has is that it's slightly quicker than the others

tawny mountain
# dusky lake If you are using dictionaries, yes newtonsoft can help you, make sure to use the...
public struct SaveData
{
    [FirestoreProperty]
    public string User { get; set; }
    
    [FirestoreProperty]
    public string ProfilePicURL { get; set; }

    [FirestoreProperty]
    public int NumberOfWatchedAds { get; set; }

    [FirestoreProperty]
    public int CorrectAnswers { get; set; }

    [FirestoreProperty]
    public int WrongAnswers { get; set; }

    [FirestoreProperty]
    public float FastestSavedTime { get; set; }

    [FirestoreProperty]
    public int FiftyFiftyCount { get; set; }

    [FirestoreProperty]
    public int AudiencePollCount { get; set; }

    [FirestoreProperty]
    public int SkipQuestionCount { get; set; }

    [FirestoreProperty]
    public int PlayerGemCount { get; set; }

    [FirestoreProperty]
    public bool RemoveAds { get; set; }

    [FirestoreProperty]
    public object DailyRewardTimestamp { get; set; }

    [FirestoreProperty]
    public int SetBackground { get; set; }
}
thin aurora
#

Oh, right. It also doesn't serialize properties. So this struct will not work either.

#

Basically everything in .NET is properties when it comes to exposing data, rather than fields. It's just Unity that had to be special

#

So apart from some quirks with Unity types, Newtonsoft will always be the better choice

dusky lake
#

public object DailyRewardTimestamp { get; set; } why is your timestamp an object ๐Ÿ˜„

tawny mountain
tawny mountain
dusky lake
#

yes, newtonsoft is also a drop in replacement, i think you only need to change the import and you are fine

thin aurora
#

Technically you can work around the issues but this is a lot of extra code and bloat

dusky lake
#

dont reinvent the wheel ๐Ÿ˜„

thin aurora
#

No, obviously. I'm just saying that it's possible

tawny mountain
tawny mountain
dusky lake
#

dont use the git version

#

if you download it from git it doesnt containt the fixes for some build targets

tawny mountain
#

got it added by name in package manager , the git has instructions , thank you

#

Version 3.2.1

tawny mountain
#

ok seems that json utility was the issue

the following screenshot shows thqat it's now filled with data and not empty

#

I'll just have to remove the image url and the timestamp maybe or convert them to a proper data type before saving like a string

dusky lake
hexed sorrel
#

I'm trying to make a system where a signal travels outwards at the speed of light, and then various telescopes around the universe can receive it. My first thought was to use colliders and detect when they collide, but setting the size of a sphere trigger via script (for the signal), it doesn't detect when the telescope starts being inside. I'm considering using a list of signals and just iterating over it every once in a while to see whether telescopes can detect the signals, but that seems inefficient. Does anyone have any ideas for how to make this work?

dusky lake
tawny mountain
hexed sorrel
dusky lake
#

just run the check in update, no need for a coroutine

#

comparing two floats (size and cached distance), even going through a list of hundreds of them and comparing each is not a performance concern

#

unless you want millions of telescopes and thousands of sources, then i would think about optimization ๐Ÿ˜„

hexed sorrel
#

Thanks!

maiden ingot
#

Hello, I have this code and what happens to me is that if I don't click on the perfect microsecond, the attack doesn't come out. Is there a way I can make it so that if I click while waiting for the second one, it will be saved and the next attack will be made?

#

sorry if my english is bad

leaden ice
#

You would change that

#

make a loop and yield return null to wait one frame in the loop

#

and use a timer and check the input every frame until the time elapses

#

e.g.

float waitTime = 1f;
float timer = 0;
bool inputPressedInTime = false;
while (timer < waitTime) {
  timer += Time.deltaTime;

  if (Input.GetWhatever(...)) {
    inputPressedInTime = true;
  }
  yield return null;
}
if (inputPressedInTime) {
  //...
}
else{
  //...
}
formal rampart
#

I'm trying to make a chess game, and I'm currently designing the subsystem that I might need. I've come up with this following: grid, piece, input, logic-rules, game state, ui, ai. My first goal is to make a grid and make a pawn class to move all around the board. My questions are:
Does this approach seem decent?
Any information anyone has on making a reusable grid system?
Anyone willing to give an idea of how a piece would communicate with the grid?

leaden ice
maiden ingot
short quiver
#

sorry if my english is bad

#

Hi, I'm working on a game with hitboxes in 3D space, and I've created Hitboxes as Monobehaviors with Colliders and such. I've programmed the hitboxes to update transform properties to hardcoded values on a per-frame basis (position, rotation, and scale). My question is, is there an elegant way for me to store the transform transformations? Could I come up with something better than the following?

[SerializeField] public Vector3[] positions;
[SerializeField] public Quaternion[] rotations;
[SerializeField] public Vector3[] dimensions;
private Transform Origin; // the <typeparamref name="Transform"/> about which the hitbox is anchored
private int Frame = 0;
// ... more member fields

void FixedUpdate() {
  // ... abbreviated snippets in FixedUpdate
  Vector3 offset = positions[Frame];
  transform.position = Origin.position+Origin.rotation*offset;
  // ...
  Frame++;
}

Basically, the arrays of Vectors hold the new transform state on each frame. I might consider some sort of struct that tracks all ~9+ values into one array element, but as I understand, Transform can't exist independent of a GameObject.

lean sail
maiden ingot
leaden ice
tawny elkBOT
signal moon
#

Hello!

#

The problem here is:

#

When i interact with my pc, i go into the new camera, but when i want to exit it, i can't, using e is not working. And also i don't have any idea why, but this error is showing, despite everything assigned. It might have something to do with raycasting....

#
Interaction.Update () (at Assets/Scripts/Interactions/Interaction.cs:23)```
leaden ice
#

this almost certainly means you don't have any MainCamera in the scene

signal moon
leaden ice
#

(It needs to be an object with a Camera component and the MainCamera tag)

leaden ice
signal moon
leaden ice
#

the camera is disabled

signal moon
#

oh, so thats why it triggers when i go into pc camera

#

in this moment i disable main camera

leaden ice
#

then you shouldn't be trying to do raycasts from the camera while it's disabled

signal moon
#

yea, i can as well disable it

#

its not usefull for pc camera anyways

#

but ok, so i fix it by just giving pc camera main camera tag?

leaden ice
#

The better solution here is probably to use Cinemachine, because then you only have one camera in the first place

#

But you could also manage your references to the different cameras

signal moon
#

I have interaction with many things like doors. When i interact with a PC, it is supposed to go on closer look to monitor screen.

leaden ice
#

Or just check if the camera is null and return early here

#

it depends what you want

leaden ice
#

I doubt it

leaden ice
#

so you can just check if either you're in that mode or if the camera is null

#

and return early

#

or just disable the interaction script while in that mode

#

lots of options

signal moon
#

So the expected behavior is: I click e on pc, i get in the pc camera, i press e again, and i switch to normal camera once again.
I can disable raycasting and interaction while im using computer.
I can give my pc camera main camera tag

#

when i give maincamera tag to the computer camera and the actual main camera then my raycasting goes to shit

leaden ice
#

well yeah it will pick one at random

#

IDK why you would do that

#

you don't want to raycast from the computer camera

signal moon
#

No, i don't need raycast or interaction when im on computer mode. All i want is to be able to switch through the cameras

#

can i make the camera not usable but not disabled per se

leaden ice
#

instead of multiple actual unity cameras, it uses just one camera and a bunch of "virtual cameras"

#

Then you won't need to worry about this as there is only ever one MainCamera

signal moon
#

hmm, ill look into it, i used it 2 years ago, but i long since forgot what it did

sonic swan
#

I have an enemy that when it moves its supper jittery

#

Idk why

#

It's not to do with fixed update or anything everything is on regular uodate

leaden ice
#

or you're breaking the Rigidbody's interpolation

#

You'd have to show your code and show the object's inspector

leaden ice
#

Not sure what's unclear about that exactly

sonic swan
#

My rigidbody is set to interpolate

leaden ice
#

but a Rigidbody moving without interpolation will move at the physics update rate

#

Well - your code is likely breaking the interpolation then

#

Can you please share your code

sonic swan
#

Sure

#

It's a bit big xuz I worked on it a bunch on my old pc where.my frames were so low that I didn't see the jittering

leaden ice
#

DOn't worry about how big it is

#

!code

tawny elkBOT
sonic swan
#

here

leaden ice
sonic swan
leaden ice
#

Thank you

#

Your problem is here:

        if (rb.velocity.x > 0.05f)
        {


            transform.localEulerAngles = new Vector3(0, 180, 0);
        }
        else if (rb.velocity.x < -0.05f)
        {


            transform.localEulerAngles = new Vector3(0, 0, 0);
        }```
#

because you are directly modifying the object's Transform each frame, it is breaking the interpolation you set up on your Rigidbody

sonic swan
#

let me check

#

still happening

leaden ice
#

what did you do

sonic swan
#

i remeved the linesof code

#

those

#

and its still jittering

leaden ice
#

Can you show:

  • The inspector for this object
  • How your camera works?
#

(do you have a camera that moves?)

sonic swan
#

yes

#

my camera moves based on update clock

leaden ice
#

Can you show that script as well?

sonic swan
#

nvm i relazid what i did

#

i had another script also enable that was messing everything up

sonic swan
leaden ice
#

only do it when you change directions

sick latch
#

I'm using Vector3.RotateTowards to have 8 directional rotation from my arrow keys by using this function:

Vector3 vector3 = Vector3.RotateTowards(transform.parent.transform.localEulerAngles, targetVector, 0.05f * Time.deltaTime, 0.5f);
transform.parent.transform.localEulerAngles = new Vector3(0, 0, vector3.z);

What's the easiest way to adapt this function to not take a long way round when wrapping around over 360?

sonic swan
leaden ice
sick latch
#

Ah

#

Whats an equivalent I can use for eulerAngles?

leaden ice
#

basically - doing anything with euler angles is usualkly a mistake

#

I would not use euler angles

sick latch
#

I tried using quaternions but it caused a lot of problems due to needing to go over 180

leaden ice
#

you should do something like this instead:

Vector3 currentDir = transform.parent.up;
Vector3 targetDir = /* whatever 8 way direction vector you want */
transform.parent.up = Vector3.RotateTowards(currentDir, targetDir, Time.deltaTime * .05, 0.5f);```
#

You don't need quaternions

#

but quaternions would also work just fine here

#

not sure what you mean about "needing to go over 180". Those are the woes of someone using euler angles

sick latch
#

I spent 4 hours last night shouting at quaternions so aren't really in the mood for any more of them

leaden ice
#

well my suggested solution doesn't use them so

sick latch
#

Yeah, thanks for that

#

This is what was happenign with Quaternions, it refused to be anything other than 180

leaden ice
#

it would be an issue with your code

sick latch
#

Slerp'ing between the target and beginning rotation then applying the result to the parent rotation

#

There was somethign going wrong with it but couldnt figure out what

leaden ice
sick latch
#

Yeah I would but it's long gone

sweet verge
#
[RequireComponent(typeof(CharacterController))]
public class Movement : MonoBehaviour {
    public Vector3 velocity = new(0, 0, 0);
    public Vector3 acceleration = new(0, 0, 0);
    public CharacterController controller;

    public void accelerate(Vector3 force) {
        acceleration += force;
    }
    private void Start() {
        controller = GetComponent<CharacterController>();
    }
    private void Update() {
        velocity += acceleration * Time.deltaTime;
        acceleration = new(0, 0, 0);

        controller.Move(velocity * Time.deltaTime);
    }
}
[RequireComponent(typeof(Movement))]
public class Gravity : MonoBehaviour {
    [SerializeField] float rate = 9.81f;
    [SerializeField] float terminal = 53.9f;

    private Movement movement;

    private void Start() {
        movement = GetComponent<Movement>();
    }
    private void Update() {
        if (movement.controller.isGrounded)
            movement.velocity.y = 0;
        else
            movement.acceleration.y -= rate * Time.deltaTime;

        if (movement.velocity.y > terminal)
            movement.velocity.y = terminal;

    }
}

so its like
Gravity -> requires Movement -> requires CharacterController

#

@hexed pecan

somber nacelle
#

you reset it's downward acceleration every frame

#

which means, unlike real gravity, it does not actually accelerate

sweet verge
#

i reset acceleration but not velocity

#

acceleration represents forces so you typically zero that every frame

#

because you can't assume that a force is constant

#

gravity could be turned off the next frame

#

or, the engine thruster to the rocket could stop being pressed on the next frame

#

so accel always gets assumed to be zero at the beginning/end of frames

somber nacelle
#

okay sure, and what actual debugging have you done to ensure the values are what you expect them to be?

sweet verge
#

i assumed i must be doing something obvious like an extra delta time somewhere

#

wanted to see if anyone could see it easily

somber nacelle
#

if you have some idea of what it might be, why not test that theory instead of asking here?

sweet verge
#

what would i test

#

the delta math is hard for me right now

#

if anyone sees an obvious bug that I can fix, that is much much faster

eager fulcrum
#

Hey, I'm adding throwing to my topdown game and my math is not mathing

Vector3 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
float distance = Vector2.Distance(transform.position, mousePos);

if (distance > MaxThrowDistance)
{
    distance = MaxThrowDistance;
}

float horizontal = Mathf.Clamp(MaxHorizontalVelocity.y * (distance / MaxThrowDistance), MaxHorizontalVelocity.x, MaxHorizontalVelocity.y);
float vertical = Mathf.Clamp(MaxVerticalVelocity.y * (distance / MaxThrowDistance), MaxVerticalVelocity.x, MaxVerticalVelocity.y);
ItemObject thrownItem = _mapManager.SpawnItem(_selectedItem.Item, _hand.transform.position.x, transform.position.y, 1, ItemObject.ItemState.MidAir);
thrownItem.Throw(_hand.transform.right * horizontal, vertical);

flying obj:

private void UpdatePosition()
{
    if (!_isGrounded)
    {
        _verticalVelocity += _gravity * Time.deltaTime;
        _sprite.transform.position += new Vector3(0, _verticalVelocity, 0) * Time.deltaTime;
    }

    transform.position += (Vector3)_groundVelocity * Time.deltaTime;
}

private void CheckGroundHit()
{
    if (_sprite.transform.position.y < transform.position.y && !_isGrounded)
    {

        _sprite.transform.position = transform.position;
        _isGrounded = true;
        GroundHit();
    }
}

The idea is to throw item and make it land exactly at mouse pos. If mouse pos is outside the range then it should throw it as far as it can within the range towards the mouse.
It should fly along a parabola.

somber nacelle
# sweet verge what would i test

if you think it is an extra deltaTime multiplication that is something you can super easily test considering there are only 3 there.

paper tree
#

Im making Config Singleton (this script is attached to GameObject)

While Debug.Logs returns correct values on Awake later when i try use anywhere (in same namespace) like Config.Instance.AppRoot it returns empty string

using UnityEngine;
using System.Runtime.CompilerServices;
using System;
using System.IO;

namespace RPG
{
    public class Config: MonoBehaviour
    {
        public static Config Instance { get; private set; }

        #region app

        private string version = "0.1";
        // private string appRoot = Application.persistentDataPath;
        private string appRoot = Application.persistentDataPath;

        public string Version
        {
            get { return version; }
        }
        public string AppRoot
        {
            get { return appRoot; }
        }

        #endregion app

        private void Awake()
        {
            if(Config.Instance == null)
            {
                Config.Instance = this;

                Debug.Log(Application.persistentDataPath);
                Debug.Log(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData));
                Debug.Log(Application.productName);
            }
            else
            {
                return;
            }
        }
    }
}
knotty sun
#
if(Config.Instance == null)
            {
                Config.Instance = this;

????????????

eager fulcrum
#

whats wrong with this?

woeful spire
#

singleton shenanigans no?

eager fulcrum
#

thats how u make sure that there is no coppies

knotty sun
#

why would you refer to the class you are already in?

somber nacelle
#

that's the singleton pattern

woeful spire
#

if there's another instance

#

then this won't replace it.

#

There can be multiple instances of the class. This ensures that it doesn't say I AM NOW THE SINGLETON when there already is one claiming that title.

somber nacelle
#

sure accessing it through the class instead of just Instance == and Instance = this within the class is a little unconventional, but it's perfectly fine

eager fulcrum
#

you spammed ? as if they made a grave mistake

knotty sun
#

what he did shows a fundamental lack of understanding of what he is doing

somber nacelle
#

it really doesn't though

knotty sun
#

it really does

eager fulcrum
#

i hope you are joking

somber nacelle
#

how? it's literally the same thing but with more typing required. it isn't wrong, it's just unconventional. it's like typing this. before everything within the object. it isn't necessary but it also isn't incorrect

knotty sun
#

no I am not, why would the Config class refer to the Config class explicitly?

somber nacelle
#

it literally doesn't matter though, it compiles to the same thing so what difference does it make if they want to get a little extra explicit about it?

knotty sun
#

I know it doesn't matter as far as the compiler is concerned, I'm just saying it demonstrates a lack of understanding

eager fulcrum
knotty sun
paper tree
#

Yeah i lately start to rewrite many classes to use explicity to what class i refere cause whiele my project is fast growing with many files classes its start to looks so messy to call thousend of function from diffrent classes, so while im jumping every 10s between files to find something or extend it it makes way more obvious where it cames from, on what i work

And its all compiled so its doesn't really matter for optimization

paper tree
#

also atleast for me it make sense to write Class.staticprop
Instead just access static prop to keep clean diffrence between local properties and static or from object

knotty sun
#

to come back to your question, you cannot use Application.persistententDataPath in a class constructor
try

public string AppRoot
        {
            get { return Application.persistentDataPath; }
        }

and forget appRoot completely

paper tree
#

I see thanks i found work around with dependencies and scripts order but that would be such a overhead for just getting path

somber nacelle
#

note that if you need to access that on another thread you need to go back to having a field for it, but make sure to assign to the field inside of Awake rather than the field initializer

#

or an auto-property with a private setter

paper tree
knotty sun
paper tree
#

Well i didnt even got any log message just got empty string ๐Ÿ˜…

knotty sun
#

yep, bad Unity error handling

swift falcon
#

Heya people, can someone please tell me how to make a Graph in script (like a one in trail renderer)?

hexed pecan
#

You want to draw some lines or?

plucky inlet
#

I guess the animation curves in inspector?

white birch
#

I can't get the freaking shape to stay in the mesh filter..

anyone have any clue what I am doing wrong.. I have the shape, and I assign it to the mesh filter... but i get this

MeshFilter and Mesh assigned.
Mesh was reassigned to MeshFilter.
Vertices count: 202
Triangles count: 600
Mesh was reassigned to MeshFilter.

#

It is supposed to reveal the FogOfWar.. but the mesh wont stay

leaden ice
white birch
#

if i put a cube on it... it works

#

The shape is being created from the raycasting and changes dynamically

leaden ice
#

ok... so, show your code?

white birch
#

hatebin wasnt working

leaden ice
#
        // Ensure mesh is updatedd
        if (meshFilter.mesh != visionMesh)
        {
            Debug.LogWarning("Mesh was reassigned to MeshFilter.");
            meshFilter.mesh = visionMesh;
        }``` This part isn't necessary tbh
#

you are assigning it in Start

#

When you say it "won't stay"? When does it "go away"?

white birch
#

it never reassigns

#

I took that code out you mentioned.

#

so it get assigned.. but since the shape is dynamic cuz it is made with rays. I am guessing it gets cleared?

leaden ice
#

I mean you are literally Clearing it every frame

#
visionMesh.Clear();```
white birch
#

I thought it would need to be cleared and reassigned since the shape changes?

leaden ice
# white birch

What is it printing in terms of the triangles and vertices?

white birch
#

or is that wrong

leaden ice
#

does it keep printing reasonable numbers each frame?

leaden ice
white birch
leaden ice
#

What material are you using?

#

My guess is that your problem is probably related to the fact that you are never assigning any UVs to it

#

What are you expecting it to look like?

white birch
#

I want it to cut out the shape based on what you see in that picture

#

as the player moves the shape will change

leaden ice
#

I understand that

white birch
#

The material and shader are correct because once I put a different mesh filter on it. the transparency works

#

so the UV thing is probably somethng i need to look into

leaden ice
#

one thing you're doing wrong here btw is that the vertex positions need to be in local space

#

So unless this object is always at (0,0), things are going to be off

white birch
#

crap

leaden ice
#

Oh actually

#

I think you're handling that properly

#

because you're doing vertices.Add(direction * hit.distance); instead of hit.point

#

it won't account for scale properly though

#

it would be better to do vertices.Add(meshFilter.transform.InverseTransformPoint(hit.point));

white birch
#

Ok, and you mean for scaling.. like different resolutions ?

leaden ice
#

no i mean if your object is scaled

#

like Transform scaling

#

or rotation

#

which may not be something you plan on doing

white birch
#

Oh ok yeah rotation as the player moves and looks, so that could be an issue

#

So you are thinking since the mesh filter clear should be removed? or how can I keep the shape to dynamically update like I am trying.. this has been a headache its been a few days of messing around and I keep starting over.

#

Feels like it shouldnt be so hard..

hexed pecan
#

Whats the issue again - does the mesh appear invisible?

white birch
hexed pecan
#

If its an UV issue then it should be an easy fix - just add a UV coord for each vertex, they are already in 2D space

white birch
#

Do you think that is why the filter is blank? I am newer to this.. this probably would have taken most of you a few minutes lol. its been 3 days for me now

hexed pecan
hexed pecan
#

You didnt give a name to your mesh

#

So it just looks like it is blank

white birch
#

Oh ok. makes sense

#

That is bad practice lol cuz it confused me

#

Ok.. so UV is what i need to look into, thank you both for your help

#

you think that is the main issue correct?

hexed pecan
#

Not really, except if your shader uses UVs

#

Also make sure your triangles are not upside down

#

From a quick glance at the code I think they should be upright tho

#

You can create the UVs very similiarly to how you created the verts

daring cove
#

Hey,

I'm having an issue with rotating a turret towards a target angle.
The turret is supposed to rotate at a fixed traverse speed in degrees per second.

Clamping the rotation speed leads to the turret traversing with an easing towards the target angle when delta angle is smaller than the traverse speed.
This means that the time to traverse towards the target angle is far longer than it should be. This leads to the turret not being able to aim for first order intercepts or any moving target.
Making the rotation speed always the maximum with the sign of delta angle leads to the turret always rotating at traverseSpeed * Time.deltaTime. This means that the turret traverses over the target angle this leads to oscillation that throws off the turrets aim. Besides not being desired behaviour.

How to calculate when this oscillation will occur and subtract it from the traverse amount?
Here is the logic for calculating the traverse amount that later in its lifetime will be inputted to Transform.Rotate.

#
// this is the target euler angle for the turret
float targetAngle = -targetEulerY;
// turrets euler angle
float turretAngle = -turretTransform.eulerAngles.y;

// Calculate shortest angle between target angle and turret angle.
float deltaAngle = Mathf.DeltaAngle(targetAngle, turretAngle);
bool deltaAngleIsPositive = deltaAngle > 0;

// get current maximum traverse speed deg/s
float effectiveTraverseSpeed = EffectiveTraverseSpeed;
float traverseSpeedPerFrame = effectiveTraverseSpeed * Time.deltaTime;

// Clamp angle to set fixed rotation speed
float traverseAmount = Mathf.Clamp(deltaAngle, -effectiveTraverseSpeed, effectiveTraverseSpeed);
float deltaAngleSpeedPerFrame = traverseAmount * Time.deltaTime;

// Get maximum traverse speed by checking if delta angle was positive.
traverseAmount = deltaAngleIsPositive ? effectiveTraverseSpeed : -effectiveTraverseSpeed;
float maxTraverseAmountSpeedPerFrame = traverseAmount * Time.deltaTime;

// Calculate turret's angle next frame
float turretAngleNextFrame = turretAngle + maxTraverseAmountSpeedPerFrame;

// Get signs for comparison.
int aSign = deltaAngleIsPositive ? 1 : -1;
int bSign = Mathf.DeltaAngle(targetAngle, turretAngleNextFrame) > 0 ? 1 : -1;

// will over compensate with traverse speed if the signs are not equal and if used delta angle input is smaller than traverseSpeedPerFrame.
bool overCompensatedNextFrame = (aSign != bSign) && deltaAngleSpeedPerFrame < traverseSpeedPerFrame;

if (overCompensatedNextFrame)
{
    return 0f;
}

return traverseAmount;
#

This logic does not remove the oscillation.

leaden ice
#

euler angles are a recipe for disaster

white birch
daring cove
leaden ice
#

the euler angle is still problematic though even if you do DeltaAngle

#

because an euler angle cannot be taken in isolation

#

you might get (0, 180, 0) or you might get (180, 0, 180). Those are equivalent

#

and if you only are looking at a single axis (y) you will not note a difference at all between (0, 0, 0) and (180, 0, 180)

#

So - I'll warn again against reading euler angles from the Transform and acting on them - it is a pitfall

daring cove
#

Yeah I've moved on from reading euler angles in my code. This is unfortunately the only area of my project were I haven't got to refactoring that yet.

hexed pecan
#

Could also substitute it with Vector3.SignedAngle(Vector3.forward, turretCurrentForward, Vector3.up)

#

If im thinking straight ๐Ÿค”

daring cove
#

What is this calculating?

hexed pecan
#

The angle of the turret's forward along the world Y axis

#

From Vector3.forward which I would consider zero

daring cove
#

Cool, I'll put that in my vector math struct

hexed pecan
#

So basically eulerAngles.y but without the issue that Praetor mentioned

calm mountain
#

So whenever I start my game, it crashes the editor (or built version) and closes it completely. How can I determine what causes this?

#

Since I don't have a console to look at

spare dome
#

you can look at the !logs

tawny elkBOT
#
๐Ÿ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

merry stream
#

could anyone suggest a efficient/performant to create a melee telegraph in unity 2d? Im trying to create something like a red area that follows a physics.overlapcircle

#

would the best way to do this just be by instantiating a object with some image or would linerenderer or something like that be easier?

nova leaf
#

hard to explain but
i want to spawn my spaceships at my shipyard's spawnpoint transform, at the furthest/rearmost point of the ship, so when spawned, the furthest point of the back of the ship is at the spawn point, so it doesn't matter how big the ship is it always fits and points away from the spawn

brazen nest
#

How do you guys make GUI with code?

compact perch
#

Imo it's better to set it up manually in the hierarchy window, using code just for things like animations,interactions, updates based on gameplay etc

brazen nest
compact perch
#

Yeah

brazen nest
#

KK, I haven't delved much into it yet, as I'm still learning the basics of Unity, but I did attempt it awhile ago and could not figure it out lol

#

I've made some games in gamemaker2, and javascript using HTML/CSS, Unity is much more complicated haha

compact perch
#

But you're not restricted to just events, like for example you can have a script on the panel that will resize on app start to fit screen width of the device or smth, but it is nice to have "a base" that was set by prefabs

brazen nest
#

Right

#

I was also curious about player animations, how do people usually handle those? programatically or using the GUI Unity has provided

compact perch
#

That depends. For things like making a game object floating in space based on simple sine wave it's easier to do with code, but for skinned meshes and blending there's a whole workflow on animator components

brazen nest
#

Damn, Ill worry about animation after I get all the basics down then xD

compact perch
#

Iirc the very first of catlikecoding (which I highly recommend as it is gold) tuts covers both the basics of unity gameobjects and animating them via code to make analog clock. Learning about animators, state machines and stuff can be done later preferably

#

But for basics there is plenty of other valuable tutorials on yt and unity page

brazen nest
#

kk, I prefer to learn by doing xD, I'm too adhd to follow tutorials

compact perch
#

If you crazy enough you can try diving into DOTS immediately, before you get to much OOPed by MonoBehaviors ;p

brazen nest
#

I can read stuff, just people talking at me, youtube tutorials not the best

compact perch
#

Got it

brazen nest
#

Maybe its just all the ones I've seen suck, theyre way too fast or way too slow

#

Either way though I prefer reading lol

#

Ill check em out anyways

compact perch
#

Well, catlikecoding tutorial is text based, check it out fr

brazen nest
#

Okay great, I will

chilly surge
#

Drag and dropping in editor with UGUI will get you pretty far, only when you are doing highly dynamic and complex UI that you will want to use code only.

brazen nest
#

I just enjoy writing code for everything, I love coding xD, I find programming easier than using UGUI

#

UGUI is usually confusing on what certain things do, and code is just solid in what it tells you it does

still gate
#

Can anyone tell me how to manipulate line renderer material in run time I have a project to show and can't figure it out

brazen nest
compact perch
#

Yes

chilly surge
brazen nest
compact perch
#

It's aiming more at art in later tutorials, but "Basics" section cover programming pretty well

chilly surge
#

I also have good amount of experience in web dev and yeah, UI in Unity, especially UGUI and drag and dropping like a caveman, is so painful in comparison. But it's good enough for most cases and gets the job done, because game UIs usually aren't that complex comparing to web/desktop apps.

compact perch
#

Personally I prefer to write code for UI as well, but UGUI is intuitive as walk in the park and letting you make simple things waaaaay faster

#

Maybe having a big tolerance after messing with crappy UEFN gui though xd

brazen nest
#

Yeah I wasnโ€™t sure whether to learn unreal or unity for my first 3d engine, so far I think Unity is pretty good.

#

Just difficult starting out, same as any engine really

compact perch
#

For me the choice is pretty simple. If you prefer manual gearbox go for unreal unless you have poor hardware or want to make "simpler" apps

brazen nest
#

Everyone I asked told me Unity gives you more freedom vs unreal

#

Like unreal lays out everything for you more

#

Not really sure what they meant, because I have no idea what the difference between them is lol

compact perch
#

Well it may be true if talking about Editor. But when it comes to programming language, C# handles much more things automatically. Whether it is good or not it's a matter of preference

brazen nest
#

Ah I see what you mean

#

I did read that can be an issue when trying to configure networking eventually, or garbage collection

#

But even then, arenโ€™t you able to change the functionality of those things? Or are they locked. Iโ€™m still a noob

compact perch
#

Forget about networking for at least the first month of learning unity :p Messing with GC is unsafe advanced kind of thing, that you will use rarely when working with unmanaged low level stuff that is also not a topic for beginnings

brazen nest
#

But you ARE able to change those things?

#

So if you want to, you can, it will just take some effort

compact perch
#

Yeah, you can do pretty much everything you want in the engine

brazen nest
#

Awesome

#

Thatโ€™s what I wanted to hear lol

compact perch
#

Some lower level stuff could be probably achieved way easier with CPP though

brazen nest
#

Yeah definitely

#

If you choose to program in c++, how could you configure that in Unity, or is it not possible?

compact perch
#

Ugh... I think it's something about Native Plugins if I'm not wrong, but didn't do any research on the topic tbh

#

Just stick to C#, it will drive you all the way basically

brazen nest
#

Kk

#

I think itโ€™s good for me to learn anyways because my education teaches me c++ but not c# lol

#

C# seems extremely similar to Java so far

compact perch
#

Unity provides quite safe API like UnsafeUtility to work with marshaling, so you can basically forget about c++ at all, at least if you don't write .dlls in it

#

But again - didn't do things like this in unity personally so maybe wrong

brazen nest
#

Kk thankyou for your time sir

compact perch
#

Np uw

brazen nest
#

Im going to checkout those resources in the morning, Iโ€™m burnt trying to figure out this python project for school, Iโ€™m making some game similar to minesweeper lol

#

Iโ€™m learning python while trying to make it, so the syntax was holding me back for ages

brazen nest
#

Sometimes I wish we had that machine from the matrix that just downloads the mastery of a skill into your brain lol

#

But then there probably would be no reward or gratification to learning anything

cosmic rain
#

Might be cheaper to hire a gamedev company to develop your game instead.

brazen nest
#

Hahaha youโ€™re right ๐Ÿ˜‚

#

I seriously think programming is one of the coolest things Iโ€™ve ever discovered, and I want to know all of it, Iโ€™ve been programming for just over a year and a half and moved my entire hobby/ future career this direction. It feels like such a slow process getting into it though. Especially when I see people around my age online writing entire game engines (actually now that I think of it, itโ€™s usually guys 30+, Iโ€™m 24)

#

But everyday Iโ€™m so motivated to learn more, if I donโ€™t get into an adhd hyper focus hole of grinding some game

#

Iโ€™ll fire up Unity and just try to understand basic movement and physics tweaking code slightly for like 6 hours each day lol

#

If I donโ€™t have assignments due ugh

#

I sometimes wonder if Iโ€™m studying it all wrong, and thatโ€™s why it takes me so long

compact perch
#

maybe its not a common statement, but i think writing entire engine from scratch (provided you know the language and have a good plan) can be just the same challenging as learning ENTIRE unity api, because it is just huge. So 3 steps forward - 2 steps back - do research - repeat is a good way to learn it, if you aim to be more generalist than specialist. Otherwise just master a single skill before switching to the next

brazen nest
#

This discord is great, Iโ€™ll definitely be in noob help a lot lol

dire crown
#

Is there any way to get the current shadow distance that is set?

#

Ah found it QualitySettings.shadowDistance;

dusk apex
fringe ridge
#

I have a tilemap, that i'm placing my buildings on, now the problem is, that the buildings (fences in this case) that are further away in the tilemap, overlap with the ones that are closer to the camera, making this effect. Any ideas how I should approach this?

mystic fox
#

Hi all, when using Unity Gaming Services for User Authentication with user/password, is there a way for the user to recover the password in the case of forgetting it? I can't find in the documentation.

maiden ingot
#

Can someone explain me why this shows like its wrong?

#

It should look like this i think...

knotty sun
leaden ice
#

or look in your unity console

maiden ingot
maiden ingot
plucky plinth
#

guys is there a way to modify a value declared outside of a corroutine
when changing the parameter value that is tied to that outside variable ?

leaden ice
#

and explain what the end goal is?

plucky plinth
#

sure gimmie a sec

#
x = 1;

Ienumerator corroutine(int var){
    var = 90;
    yield return null;
}

void update(){
    StartCorroutine(corroutine(x));
}
#

idk why the outside value doesnt change

#

isn't it supposed to change when used as a paremeter ?

leaden ice
#

value types are pased by value into functions. aka a copy is made

knotty sun
#

no, it is passed by value not reference

plucky plinth
#

oooohhh

leaden ice
#

this has nothing to do with coroutines btw

#

the coroutine is a red herring

#

It's the same for any method

plucky plinth
#

yeah i kinda have no idea what to even search in the net

leaden ice
knotty sun
leaden ice
plucky plinth
#

damn thank you both very much

maiden ingot
#

Im doing a "Combo System" for my game, i've reviewed all the code and the only part that doesn't works is this. It doesn't receive the input. I tried putting "Attack()" in the update, removing it and changing the input and it doesn't work. Does someone know why?

leaden ice
#

Have you tried actually calling it?

maiden ingot
leaden ice
#
void Update() {
  Attack(); // << this is how you call a method
}```
maiden ingot
#

and it doesnt work

leaden ice
leaden ice
#

calling methods works, I can assure you of that

maiden ingot
#

wait 1 second

knotty sun
#

instead of just logging the outcome, log ALL of the steps in your code

maiden ingot
leaden ice
#

mp4 please to embed in discord

maiden ingot
leaden ice
leaden ice
maiden ingot
maiden ingot
leaden ice
#

Can Receive input is false, so your if statement won't pass

#

you need to debug your code

#

Start using Debug.Log more and print values out and test your assumptions

maiden ingot
#

you're right

#

Sorry for bothering

#

next time i'll be sure to debug my code

short quiver
#

Im doing a "Combo System" for my game, i

halcyon steppe
#

is there a way to read out the speed that an animation is played back at while the animation isnt currently playing?

I am trying to Invoke something after the duration of an animation and I want to be able to adjust playback speed without needing to adjust the script each time.

leaden ice
halcyon steppe
#

Is there any other way to do this? cause I am trying to avoid the animation events because of reasons too long to explain here.

leaden ice
#

StateMachineBehaviour is the next best way

#

but AnimationEvent is by far the best

jolly stratus
#

Guys, I'm building for mobile, is there any way to increase the scroll fps of scroll view? It's scrolling at 30fps and looks choppy

halcyon steppe
jolly stratus
vagrant blade
#

The scroll view is never smooth, but one thing you can do is ensuring you using canvas groups and not causing unnecessary redraws. Learning how to optimize the UI is a whole thing that you can look into:
https://unity.com/how-to/unity-ui-optimization-tips

Additionally, if you're scrolling through a lot of repetitive content (like leaderboards, etc.), you can object pool and reuse objects.

jolly stratus
vagrant blade
#

No

#

Scroll FPS is performance driven. You can't just "make" it be smoother.

jolly stratus
vagrant blade
#

Unity's UI is extremely bad performance in general

#

There is a lot of overhead that happens, which is why you have to optimize it as much as possible by ensuring you're not doing anything unnecessary (refer to the link)

mellow sigil
#

Also the UI fps is not separate from the game fps. If the game runs at 30 fps then the UI runs at 30 fps. The default framerate is 30 or 60 on many mobile devices

waxen burrow
#

!code

tawny elkBOT
restive juniper
#

Hey guys! I need some help ๐Ÿ™‚
So I want to have different Cards with different effects in my game. I started by creating a Card Scriptable Object that has different Data and my idea was to have a property of type CardEffect where I can assign different Classes of type CardEffect that derive from the main class CardEffect and implement the method UseEffect(). Now I want to create CardEffect like "DealDamage" where the amount can differ from card to card and I want to be able to assign the damage value when I assign the CardEffect to the Card-Asset from the Scriptable Object.

Hope that was clear.. ๐Ÿ˜„

waxen burrow
leaden ice
#

at least make an intermediate varaible first

#
string tag = obj.tag;
if (tag == blah || tag == foo)```
#

every time you call obj.tag it allocates a brand new string, which needs to be garbage collected

waxen burrow
#

oh thats awful

leaden ice
#

I would say the switch statement is better in either case

waxen burrow
#

switch cases not having their own scope is one of the weirder things I've learned about C# in a while

leaden ice
brazen nest
leaden ice
#

I'd love to say yes

#

but no

brazen nest
#

hahaha

waxen burrow
thick terrace
#

it's the same in C++

earnest gazelle
#

The instance ID of an object acts like a handle to the in-memory instance. It is always unique, and never has the value 0. Objects loaded from file will be assigned a positive Instance ID. Newly created objects will have a negative Instance ID, and retain that negative value even if the object is later saved to file. Therefore the sign of the InstanceID value is not a safe indicator for whether or not the object is persistent.
So, can we distinguish between dynamic spawned gameobjects and preloaded gameobjects by checking sign of instance id?

hexed pecan
#

Therefore the sign of the InstanceID value is not a safe indicator for whether or not the object is persistent.

#

I think it's not an issue in a build, but I could be wrong

#

From what I understand - if you save it to an asset, it will stay at negative instance ID until you reopen unity

earnest gazelle
waxen burrow
jolly stratus
leaden ice
#

I don't think those scopes are doing anything btw

waxen burrow
#

oh yeah not anymore

#

oops

waxen burrow
#

doesn't have to be perfect, just trying to avoid bad

leaden ice
rose fulcrum
#

Not sure if I should ask this question here or in #archived-game-design BUT.
I'm trying to figure out the best approach to getting this to work:
The setup looks like this:
Both physical screens are actually one mesh where both screens share a single UV map.
What's currently displayed on the screens is done by using a single material with a render texture that is supplied with a second camera.
Every element is made with uGUI.

During playtime, there is a CinemachineVirtualCamera that is set to hard look at a game object I call "camera target."

What I want:

  1. I want to add a "cursor" to the monitors, it would function how a normal desktop cursor would.
  2. I need the cursor to actually be functional and actually "click" on UI elements.

Where I'm lost:
I'm not sure what approach would be best.
I've considered casting Physics Ray onto the screen, then figuring out where on the UV map that ray hits, but I'm not sure where to go from there. I'm sure I could figure out how to get the mouse to move, but I'm not sure how I would go about getting mouse clicks. Any suggestions?

#

Raycast -> UV Map Coords -> Canvas Coords -> ?

waxen burrow
leaden ice
waxen burrow
#

Fair

leaden ice
#

that does the translation you described (raycast to hit point to uv coordinate)

rose fulcrum
waxen burrow
#

I am making a โ€œparameterizedโ€ hallway. Basically a cube of planes facing inward where the player is positioned inside.

I have a hallway object (script is attached to) that is the parent of all the cube faces(planes)
There are three variables: length, width and height. The cube scales to those values growing from the back edge.

The tags are to identify which face is which so they can be positioned properly.

-# Iโ€™d send more code / a pic of the hierarchy but I donโ€™t have my computer atm

leaden ice
rose fulcrum
#

thats what I'm usin

waxen burrow
#

Yes

rose fulcrum
#

sorry, I don't mean to sound rude or anything, I know I left out a ton in my description of my scene. There's just a lot

leaden ice
# waxen burrow Yes

You could use a component like this:

public enum HallwayPart {
  LeftWall,
  RightWall,
  Ceiling,
  Floor
}

public class HallwayPlane : MonoBehaviour {
  public HallwayPart Part;
}```
#

Then your other code can look at that instead of the tag

waxen burrow
#

So classes over tags for id

leaden ice
# waxen burrow So classes over tags for id

You could even do something like this:

[Serializable]
public struct PartParams {
  public Vector3 scale;
  public Vector3 position;
}

public class HallwayPlane : MonoBehaviour {
  public PartParams Params;
}```
#

And just - set this all up in the inspector

#

somethingf like that

#

this is a rough idea that needs to be hammered into something generally useful

waxen burrow
#

For sure, I understand what you are getting at, Iโ€™ll definitely implement it when I get back on later today

#

Last question about the hallway for a bit, but when it comes to adding textures to the walls, especially for greater lengths; will textures tile across it properly automatically?

shell scarab
#

not specifically a coding question per se, but for some reason Unity is not wanting to recompile my scripts? I have to keep entering play mode or restarting Unity to make it recompile. I have auto-refresh enabled.

leaden ice
shell scarab
rose fulcrum
shell scarab
rose fulcrum
#

point

shell scarab
#

Domain reload is off on the project, but I have no control over that (i'm pretty sure it's a project-wide setting, right?). But I don't think that would cause any issues like this. Doesn't cause any issues for anyone else at work. I'm only asking here because they don't have any clue as to what's happening lol

#

it's really weird, because looking at the script file I can see my changes in the preview. But looking at the inspector, I don't see my changes until I hit play (which causes it to be recompiled)

short quiver
#

Is Unity's built-in state machine editor only relevant to animations? Every time I've seen FSM visualized in a graph in a tutorial, it's regarding animations, and in every tutorial dealing with game physics, it seems that people are using text to program the state machine - what's with the discrepancy?

leaden ice
#

that's the only thing of that nature built into Unity afaik

short quiver
#

that's the only thing of that nature

shut sun
#

anyone had the editor hang with this particular message? 6.18f1

broken light
broken light
#

the vertices...

spare dome
naive swallow
broken light
#

i meant the buffer not the individual vertex

#

in other words i would much rather a pointer to the array not create a duplicate array

#

since im only using it for reading not editing

naive swallow
#

You pass in the array to use, so if you keep a reference to the array around it'll re-populate that one instead of making a new one

late lion
#

To know what part of the array is position data, you have to query its layout with the methods in MeshData.

dusk apex
tawny elkBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

ocean hollow
#

can i not use update in a script that derives form monobehaviour + something else?

#

usually my ide would finish this for me but its not giving me the option for this script

leaden ice
#

if you have any "something else"s, those would be interfaces

#

you can always have Update in a MonoBehaviour

#

make sure you don't already have one in this class for example

ocean hollow
#

i have monobehaviour and ipointerdownhandler, and no existing update function, but its not letting me add update

ocean hollow
leaden ice
#

My guess here is you have forgotten the opening bracket or something

#

given that the suggestions are interfaces

#

{}

ocean hollow
#

when i do, its colored as normal Update would

ocean hollow
leaden ice
#

show your full screen

ocean hollow
leaden ice
#

that's not the full screen...

#

but it looks fine

ocean hollow
leaden ice
#

the full screen lol, but it seems fine so don't worry about it

ocean hollow
#

but any ideas on why my ide inst working for this script?

#

it doesnt give me the option for anything else either

leaden ice
#

showing the full screen might help - perhaps it's in a different assembly or something

ocean hollow
#

i dont see anything wrong with this...

leaden ice
#

it works for other scripts?

ocean hollow
#

yeah just fine

#

different script ^

leaden ice
#

restart VS

ocean hollow
#

i restarted and it doesnt fill anything...

#

wait now it works...

#

i tried typing fixed update and it started working again

#

im so confused

terse turtle
#

I am using Scriptable Objects to handle a Wave System in my game. Each Wave Object is comprised with at least 2-4 raids. In which my WaveManager will run in the game. This system works really well, but I am going into level production and now notice something big. I need at least 28 waves per level, or more, and this seems like I will not be able to manage them. I am probably going to make something around 20-50 levels, so this could be a very hefty amount of wave SO's I need to create. Just want to know a few things:

  1. Will the amount of SO's I will have result in big Memory sizes?
  2. How should I go about managing a big amount of SO's?
  3. Is this a bad idea?
leaden ice
#

or a system where you can use a spreadsheet or something

knotty sun
#

indeed, what data changes that requires so many unique SO's?

leaden ice
#

consider even compacting the data into AnimationCurves or something

terse turtle
knotty sun
warm badger
#

can anyone suggest me any asset or method to see memory usage in runtime for android build?

warm badger
warm badger
short osprey
#

So im having the weirdest issue rn

#

I made code that handles a button press to swap to a different action map (new input system) and from that map hitting the same button it should swap back. That isnt whats happening though:

it goes from a-> b, but then trying to leave b will result in b -> a -> b.

I feel like currently when it switches maps the new one already listens to the same input press that triggered it to become active in the first place but i cant imagine that case resulting in such consistent behaviour....

let me post code

knotty sun
short osprey
#

ah I see. how would I work around that?

knotty sun
#

wait one, let me find the code

short osprey
#

sure

plucky inlet
#

Are you disabling the previous map?

short osprey
#

yes

#

w8 let me grab my relevant code

plucky inlet
#

Or we just wait for Steve, he might have the solution to the bug already

short osprey
#

sure

knotty sun
#

Ok, so this is what I do when I change the map

    public void OnConfig()
    {
        StartCoroutine(Config());
    }
    IEnumerator Config()
    {
        // Fix up for InputAction bug
        int i = 0;
        while (i < 40)
        {
            yield return null;
            i++;
        }
        //yield return new WaitForSeconds(0.5f);

        GameManager.instance.playerActions.OnDisable();
        //SceneManager.LoadScene("GamePad");
        Off();
        input.SetActive(true);
    }

basically build in a 40 frame delay so that the previous keypress disappears before changing the map

short osprey
#

thats wild

knotty sun
#

as you can see I played with different options

short osprey
# knotty sun as you can see I played with different options

i just tried a fix and it might not be the issue after all: when i set for the map switch to happen on button RELEASE instead of press, the behavriour works as intended except that it doesnt respond the very first time the button is pressed. after that, it works perfectly every time

#

well

knotty sun
#

you might need to play with the magic number, this was only tested on Windows

short osprey
#

i suppose that might be a different issue altogether

plucky inlet
#

I wonder if there is an option to invalidate the latest input events before disabling the whole system and start a new one

knotty sun
#

This is a problem I encoundered when I had actions on started and performed

short osprey
knotty sun
#

my testing shows that even if you disable the map and remove all of the events you still get this 40 frame holdover for the last key pressed

short osprey
#

thats so odd

#

does the yield return loop loop exactly once every frame?

#

i assume so

plucky inlet
#

I am more like wondering if you can replace that "magic number" with something coming from the system as callback

knotty sun
#

pretty sure I played with a range of numbers and 40 was the one that guaranteed that the previous keypress was gone

plucky inlet
#

Letting this event reset a bool until no more input is coming in for the next frame?

#

Or maybe you can store the input itself or its id and compare against it or it being null before activating the new map

knotty sun
#

I'll leave it with you to play with, if you find a better way please let me know

plucky inlet
#

@short osprey keep us on track. I dont have time for testing right now sadly ๐Ÿ™‚

knotty sun
short osprey
short osprey
#

but i cnt seem to find out how to achieve this

plucky inlet
short osprey
#
controls.Movement.GravityMenu.started += SignalGravityMenu;
GameStateManager.Instance.CurrentStateChanged += HandleStateChange;

//Further on

//This code is ran whenever the GameStateManager.CurrentState is changed
void HandleStateChange(GameStateChangedContext context)
    {
        switch (context.NewState)
        {
            case GameState.GravityMenu:
                controls.Movement.Disable();
                break;
            case GameState.Playing:
                controls.Movement.Enable();
                break;
        }
    }

The above code is in the regular movement script. the script for navigating the 'gravity menu' has equivalent methods but mirrored

#

...alternativelty i could make leaving the menu a different button to circumvent the issue altogether

#

but i dont like that

misty blade
#

I'm in a very early stage of development and encounterd a weird issue. When my character turns to the left with the script below it start really lagging. I can debug the fps and it shows steady ~300 fps and nothing major comes up in the profiler. It still looks like its dropping from 300 to around 30. If I disable the Look component it works fine again.
I was chaning X scale earlier to "rotate" the character, but added scale animations and decided to change the rotation instead.
Do you know what might be happening?

using UnityEngine;

public class Look : Capability
{
    protected override void Update()
    {
        base.Update();

        RegisterInput();
    }

    private void RegisterInput()
    {
        if (IsLocked)
            return;

        if (_controller.RetrieveMoveInput().x < 0) SetYRot(180);

        if (_controller.RetrieveMoveInput().x > 0) SetYRot(0);
    }

    private void SetYRot(float YRot) => transform.rotation = Quaternion.Euler(0, YRot, 0);
}
strange gust
#

i made a pretty simple path finding algorithm for my enemies and this one works with a visibility graph. here every Node knows which Nodes its connected to and which Nodes are visible where connections are the only thing that will block visibility. this works fine for the most part, but when you have for example 4 nodes arranged in a square with 4 more arranged in a square inside of it, the corners of the smaller square will think it can see the opposite corner of the smaller square, even though the visibility line is going outside of the polygon. any way i could fix this?

lean sail
misty blade
#

I'm sure its the SetYRot method causing the issue. If I leave it blank the stutter is gone

    private void SetYRot(float YRot) { }
trim schooner
#

Your issue sounds like camera stutter, not performance related

lean sail
#

Well yes, if you no longer rotate the object itll stop rotating..

lean sail
misty blade
#

I have a video of the left turn lags, but it barly noticable since the framerate of the video is much lower then in editor to begin with

#

I disabled the cinemachine brain on the camera, but with no result

#

the camera is also anchored so I dont see why Y rotation would cause an issue

trim schooner
#

Change the 'Update' method used on the cinemachine brain

#

I don't see any lag in that video

misty blade
#

I disabled the CM brain entirely

misty blade
strange gust
fringe ridge
#

what is the best approach for isometric sorting in unity?

plucky inlet
fringe ridge
#

it's in 2d, I'm trying to think of a way to properly render the player in front/behind a long diagonal sprite. One way I thought of was finding closest point for the collider, and then checking if a specific point for the player is above/below that point in the collider. Not sure about the efficiency of this though, especially when hundreds of objects might be in the scene

#

And I would also need to render it for multiple controllable characters

misty blade
# trim schooner I don't see any lag in that video

for some reason continuously setting the rotation caused the character to stutter (not the camera, or the framerate). Adding a simple check fixed the issue:

    private void SetYRot(float yRot)
    {
        if (transform.eulerAngles.y == yRot)
            return;

        transform.rotation = Quaternion.Euler(0, yRot, 0);
    }
knotty sun
#

you really should not do this
if (transform.eulerAngles.y == yRot)
firstly the read value of .y is probably not what you are expecting
secondly never check float values for equality

short osprey
#

whats the implementation of SetYRot

misty blade
misty blade
short osprey
#

i just saw

knotty sun
somber nacelle
# misty blade it's a good point with the comprision, but there are no calculations on the rota...

just because that is what you are setting it do does not mean that those are the only possible numbers you'll get out of it. eulerAngles are interpreted from the quaternion at the time you access them and because there are a large number of ways that a rotation can be expressed in degrees, you may be comparing against a number you didn't expect. and of course you have no control over whether a floating point number is imprecise.

misty blade
brittle needle
#

Anyone able to help me out?

#

I'm trying to create a reload for my gun, I shoot it ten times, reload it and then my animations don't work.

#

Im pretty new to coding but Im familiar with how Unity's systems work

trim schooner
#

!ask

tawny elkBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

solid relic
#

I have a struct in my script called criminals and i have a list of these structs, in my inspector i have all my criteria and stuff filled out, the struct looks like:

[System.Serializable]
public class Criminal
{
    public string name;
    public bool male;
    public bool guns;
    public bool melee;
}

each of the criminals are different, how do i get a list that changes depending on what criteria you know the criminals have?

leaden ice
#

What do you mean by "criteria", first of all.

solid relic
#

Does that make more sense?

#

Like in phasmophobia but with lists

knotty sun
#

sounds like a job for LinQ

leaden ice
#

You could literally use SQLLite or something

#

This is one option

#

It kind of depends how much data we're talking about here

#

If it's just less than 200 or so items, you can probably get away with just a list and Linq

solid relic
leaden ice
#

Use Where to filter the list for each criteria you select

short osprey
leaden ice
short osprey
#

right

#

and p => p.guns

leaden ice
#

But an enum field for the weapon type would definitely be better than multiple bools unless there's only two options

short osprey
#

didnt see that

tawdry jasper
#

Unity has this pattern of returning value or null. GetComponent<...>() or FindAction allows me to write:
InputAction x = ia.FindAction("something");
if (x != null) ....

How can I write my own function that returns a type (InputAction) or null?

mellow sigil
#
InputAction MyFunction()
{
    InputAction x;
    // ...
    if(someCondition)
    {
        return x;
    }
    else 
    {
        return null;
    }
}
leaden ice
#

if the type you want to return is a value type, null is not a valid value

#

in those cases, it's best to use the Try/Get pattern.

high otter
#

Soo I acutally don't know where to post this but this channel here seems to be the best.

I created a "Chat UI" (very very basic) with UI Toolkit and integrated it sucessfully. Issue right now is when I'm in the text input field and start typing my character starts moving too. I tried different ways now via Callbacks (FocusIn, FocusOut) to disable the character script when I'm in the input field and this works fine - but whenever the window as a whole is open and I move my character the input field gets instantly focused and the character script stops.

Tried it with disabling the focusable property when FocusOut Callback is called but now I can't access the field anymore...

Someone got a tip on how to fix this? Spend hours on that now and can't move forward...

Code of last attempt:

_messageInput.RegisterCallback<FocusInEvent>(evt =>
{
    _root.BringToFront();
    _messageInput.focusable = true;
    GameObject.Find("Player(Clone)").GetComponent<PlayerController>().enabled = false;
});

_messageInput.RegisterCallback<FocusOutEvent>(evt =>
{
    _root.SendToBack();
    _messageInput.focusable = false;
    GameObject.Find("Player(Clone)").GetComponent<PlayerController>().enabled = true;
});
hybrid relic
#

Is there any help on how to have a local like "arms only" model with animations, but have the networked players have a full body with different animations ?

i cant really find ANY help on this topic no matter how hard i google or youtube, i only find unrelevant stuff

#

Multiplayer stuff, specifically FishNet, but a Tutorial for another Framework works too

dusky lake
worn star
#

Hi i am pretty new to coding

#

i found a free behaviour tree

#

but have no idea how to use it

vagrant blade
#

And?

rigid island
#

if you're new to coding you should probably not be working on Behavior trees just yet anyway.

high otter
# dusky lake So you open the chat and it autofocuses the text bar, i am not sure how its in u...

Probably sounds dumb now but I was apparently thinking completely wrong.
My original approach was to manage all that inside the chat window script but after I thought a little bit more that doesn't makes sense when working with multiple player prefabs (multiplayer).

Refactored that whole thing now to use internal variables which I access from my player controller and then block movement from there - works fine now blobsmile

naive swallow
#

Specific questions can be answered but we don't really have anything to go off of. What the problem is, what the asset even is, what you need help with, etc.

worn star
#

but i need to make a boss , and my animator controller looks like shit

#

I need to learn it ig

rigid island
#

ya go do that lol

tough matrix
#

Hi guys.
I'm using Zenject in Unity and everything works fine in the editor, however, when I built the game, Zenject is not injecting into "loading object", thus I cannot load the game. Am I supposed to do something specific when building the game?

rocky jackal
#

THis code worked perfectly fine before but now it all of a sudden creates this error

knotty sun
naive swallow
rocky jackal
#

I swear to god it was working, i have a working version of this on github, but maybe its adifferent part thats causing the actuall issues i have and not htis error

rocky jackal
knotty sun
#

no way, make it a reverse for loop instead of the foreach

rocky jackal
#

ill try that thanks

#

maybe this error was there but the actuall gameplay part was working but its broken now and this is the only error I could find

knotty sun
#

it's definitely an error, reverse for will fix it

final fox
#

When I call this coroutine to activate a very simple UI element, the game freezes for a split second. I checked and It does not get called multiple times, and it only happens with a UI element, I know Unity redraws the canvas each time you change something, but it's not the explanation because if I activate the UI element without the coroutine, there's no spike in the profiler.

rocky jackal
knotty sun
inner shuttle
#

Hi, im having an issue with my item system where when the player picks up the item whilst moving, the item will be offset to the last position of the players hand transform, im assuming i can probably update the position somewhere but im not sure how.

https://gdl.space/wememucoce.cpp

rocky jackal
rocky jackal
knotty sun
#

odd way to do a reverse for, normally you would do Count-1

knotty sun
hexed pecan
#

@rocky jackal

knotty sun
#

that ain't a reverse for

rocky jackal
#

the for loop is working you dont need to fix that its the other logic in my game that broken

hexed pecan
knotty sun
rocky jackal
#

ok

knotty sun
hexed pecan
#

Was just showing how to convert from foreach > for > reverse for

versed loom
#

is there a cleaner way of doing this?

private char GetModifiersKey(IKeyboardEvent eventInfo)
        {
            var isShiftActive = eventInfo.modifiers is EventModifiers.Shift;
            bool isCapsActive = _isCapsActive || isShiftActive;
            
            char key = (char)eventInfo.keyCode;
            if (!isCapsActive)
                return key;
            
            char mappedKey = GetMappedKey(key);
            if (mappedKey != key)
                return mappedKey;
            
            return char.IsLower(key) ? char.ToUpper(key) : char.ToLower(key);
        }
        
        private char GetMappedKey(char key)
        {
            return key switch
            {
                '`' => '~',
                '1' => '!',
                '2' => '@',
                '3' => '#',
                '4' => '$',
                '5' => '%',
                '6' => '^',
                '7' => '&',
                '8' => '*',
                '9' => '(',
                '0' => ')',
                '-' => '_',
                '=' => '+',
                '[' => '{',
                ']' => '}',
                '\\' => '|',
                ';' => ':',
                '\'' => '"',
                ',' => '<',
                '.' => '>',
                '/' => '?',
                _ => key
            };
        }```
knotty sun
#

Use a damned array

versed loom
#

array for?

knotty sun
#

both sides of your switch

naive swallow
versed loom
#

then i have to iterate thru one of them

simple egret
#

The switch is big enough (tested) to compile into a jump table, it'll probably be more efficient than using an array

knotty sun
#

well what do you think is happening in your switch?

versed loom
#

what spr2 said

knotty sun
#

jump tables aren't magic, key still has to be evaluated

hexed pecan
#

I don't use DOTween but I suppose you should use local instead of world. Replace your DoMove line with: cs transform.DOLocalMove(Vector3.zero, 0.4f);

#

This should make it move to a local zero position which would be equal to its parent's position (playerHand)

inner shuttle
#

ill try that

rose fulcrum
#

So I'm trying to use a TMP_InputField to try and emulate a computer console / terminal.
Issue is I'm trying to do something like this:
user@localhost: (text input goes here)
Where that beginning part is bold, and the input text isn't.

I figured I could try to use rich text, but then I'd have the issue with the user being able to insert their own rich text tags.
If i try to limit what the user can type with the custom content type dropdown, then I can't add tags at all.
I'm, wondering if I'm going to have to code my own solution here, or if anyone knows something I don't.

#

And I should add that I tried setting "rich text" to true, and "allow rich text editing" to false in the Input Field component, but that still didn't work.

mellow sigil
#

Surely the first part should be a separate text element

worn star
#

failed to create agent beaucase there is no valid navmesh

#

how do i fix this

knotty sun
worn star
#

its a 2d project

#

i just added a navmesh , installed the AI packages

#

and it shows this

knotty sun
#

yes, navmesh does not work in 2D

worn star
#

oh

#

ohhh

rose fulcrum
rose fulcrum
mellow sigil
#

You can set the line-indent so that the first line is not under the prompt text

#

If the prompt is in the input field the player can edit it

keen swift
#

Someone said I should keep floats and bools in the same line instead of making a new line for each, so I did that. But i don't know if I can do the same for transforms, audio clips, audio sources, ints, game objects, TMP Text, ect.

mellow sigil
#

You mean the variable definitions?

leaden ice
#

unless they're very closely related

#

like int x, y, z; or something

#

otherwise - best to keep each variable declaration separate

somber nacelle
#

i absolutely agree with praetor's suggestion. i do just want to point out that it is possible for any type

keen swift
#

Another thing they said to me is use [SerializeField] more, because just using public makes the script use more power. Like this:

[SerializeField] private float waitTime, activeTime;

oblique spoke
somber nacelle
keen swift
#

Yea, that's what I did to one of the floats I found

#

so I kept that one stayed just public

#

Another thing, this one my friend told me; Is that I should use (other.CompareTag("Player")) instead of if (other.transform.tag == "Player")

somber nacelle
#

yes, CompareTag has a couple of benefits, it is slightly faster than comparing the strings with the equality operator, but more importantly it will throw an exception when a tag you pass to it does not exist (such as if you spelled it wrong) instead of just returning false

merry stream
#

is there a way to get pixel perfect camera to work with custom meshes on a meshrenderer in 2d?

languid hound
#

How can I use SceneManager.CreateScene to load into a new empty scene

#

Seems pretty useless to be able to create a scene and not use it

somber nacelle
#

the scene it creates is loaded additively immediately upon creation. so just unload your other scene(s)

languid hound
#

Wait really? Damn

somber nacelle
#

yes, did you not read the documentation or even test it?

languid hound
#

Oh right I missed the open instantly bit

#

So once it's open I cant do anything else?

#

I guess if I want to reopen it I have to dispose of it. It's a disposable scene anyways

lean sail
lean sail
mighty yew
#

I want to make this really easy to use for a non-programmer, any way i can add comments to explain what these do in the editor?

somber nacelle
#

either use the Tooltip attribute to add comments when someone hovers over the name or write a custom inspector, property drawer for your own attribute that draws the text, or an asset like NaughtyAttributes or Odin Inspector which i believe both have attributes that do that

mighty yew
#

The tooltip attribute is exactly what i wanted!

#

thank you!

solid relic
potent anchor
#

two mutually exclusive bools are never the answer

#

either use one bool, isMelee, and you know if it's false that it's obviously ranged

solid relic
#

I'm doing it so it can be both guns and melee though

potent anchor
#

Or use an enum if there's more than one option:
enum WeaponType {
Melee,
Ranged,
Whip,
Rocket
}

potent anchor
leaden ice
somber nacelle
#

Enum still may be a better option here though as it can potentially cover multiple cases

solid relic
#

I might try out an enum, i'll let you know how it goes

timber finch
solid relic
#
[System.Flags]
public enum weaponry {
   Guns = 0,
   Melee = 1
}

Like this?

timber finch
#
[System.Flags]
public enum Weaponry
{
   Gun = 1 << 0,
   Melee = 1 << 1
}
somber nacelle
#

use powers of 2 for flags and you can safely have multiple flags per object

timber finch
#

more like this

#

the idea is each valid type is given a positive (not 0!) value that's a power of 2

#

so you can check if something is a gun with (value & Weaponry.Gun) != 0, and if something is either a gun or melee with (value & (Weaponry.Gun | Weaponry.Melee)) != 0

#

also, checking if something is both gun and melee with (value & (Weaponry.Gun | Weaponry.Melee)) == (Weaponry.Gun | Weaponry.Melee)

solid relic
#

I also want the player to be able to cross it out, how would i put that in the flag enum?

hexed pecan
#

Wdym cross it out?

solid relic
#

So like you have: unknown, have it, or don't have it.

hexed pecan
#

I'd probably use a separate variable for that, although I'm not entirely in the loop when it comes to this conversation