#archived-code-general

1 messages Β· Page 327 of 1

pure ore
#

Okay, what would be the right way of doing this?

leaden solstice
#

Though this will be lil bit complex that you need to consider wrapping

pure ore
#

I just wanna clamp my x and y

knotty sun
#

as youve been told, euler angles

pure ore
#

so what does that mean exactly? character.localEulerAngles = Math.Clamp?

leaden solstice
#

Yes it is, angles may have range you don’t expect when it comes to clamping. 359 can be 0 at next frame. Then clamping works differently.

knotty sun
#

no

#

no. EulerA-> Quaternion ->Euler B will almost not return A ==B

pure ore
#

I'm trying to clamp the vertical axis of the player camera

knotty sun
#

not according to this ' Then you grab the euler angle, clamp it between desired values, Set it back onto the original Quaternion'

pure ore
#

This does not work ```
public Quaternion ClampXAxis(Quaternion quaternion, float minimum, float maximum)
{
Vector3 euler = quaternion.eulerAngles;
euler.x = Mathf.Clamp(euler.x, minimum, maximum);
quaternion.eulerAngles = euler;
return quaternion;
}

public Quaternion ClampYAxis(Quaternion quaternion, float minimum, float maximum)
{
Vector3 euler = quaternion.eulerAngles;
euler.y = Mathf.Clamp(euler.x, minimum, maximum);
quaternion.eulerAngles = euler;
return quaternion;
}

#

So what do I do? Because that didn't work

knotty sun
#

so you are only working with the rotation field in your code

#

@rigid island You couldn't make a vid on this could you, we have to explain it so many times

rigid island
heady iris
#

I should write some kind of blog post.

#

I have opinions.

rigid island
serene stag
split junco
#

I'm trying to send data to google forms. It works but instead of one line of data, I'm getting four lines. As such, it counts one response as four. I'm wondering why that is. Here's the data I'm trying to send:

Here's the code:

public class SaveData : MonoBehaviour
{
    private Slider slider;
    private string currentQuestionData;
    private string activeQuestion;
    private Dictionary<string, float> saveDataDictionary;
    
    private string url =
        "HiddenFor Reasons....";
    
    // Start is called before the first frame update
    void Start()
    {
        SliderTicks.OnSliderValueChanged += GetSliderValue;
        saveDataDictionary = new Dictionary<string, float>();
    }

    private void GetSliderValue(Slider slider)
    {
        activeQuestion = QuestionManager.Instance.GetActiveQuestion();
        //Debug.Log($"Slider value for question {activeQuestion} is ::{slider.value}");
        SaveFormData(activeQuestion, slider.value);
    }

    private void SaveFormData(string currentQuestion, float sliderValue)
    {
        saveDataDictionary[currentQuestion] = sliderValue; 
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void PrepareUserData()
    {
        StringBuilder result = new StringBuilder();
        string id = "ID:007::";
        result.Append(id);
        
        foreach (KeyValuePair<string, float> pair in saveDataDictionary)
        {
            result.Append($"Key:{pair.Key}---Value:{pair.Value}::");
        }

        SendUserData(result.ToString());
    }

    private void SendUserData(string result)
    {
        Debug.Log(result);
        StartCoroutine(Post(result));
    }
    
    IEnumerator Post(string data)
    {
        WWWForm form = new WWWForm();
        form.AddField("entry.hidden", data);

        UnityWebRequest www = UnityWebRequest.Post(url, form);
        yield return www.SendWebRequest();
    }
}


#

Here's what I see on Google Forms

knotty sun
#

obviously you are getting a new line every time you call the api, the timestamp tells you that

split junco
#

yes but why is that happening. As you see from the code, I'm only calling it once.

knotty sun
#

because Google is accumulating your calls

#

you are writing to the form, each write is a new line

split junco
#

It isn't. I'm simply passing a string.

heady iris
#

it looks fine the second time you did it

split junco
#

And I'm only calling the webrequest once

#

Not writing each line.

heady iris
#

from 15:04

#

perhaps it printed multiple items when you tried it at 15:01

knotty sun
heady iris
#

your code could be running it multiple times, but only under certain conditions

split junco
#

I do. But you're saying it's writing multiple times. Show me where I am calling write function multiple times?

heady iris
#

you'd need an example where there's one item in the log and many items in the form

#

so far, you do not have such an example

dawn nebula
split junco
heady iris
#

you've clearly hit the API four times at 15:01

#

since there are four responses

knotty sun
rigid island
#

how do you know its dynamic

dawn nebula
knotty sun
rigid island
heady iris
#

i think everyone here knows that hitting the API again will create another response

knotty sun
#

probably because he ran 4 time in quick succession withour checking inbetween

split junco
#

Webrequest needs to be in a constructor.

heady iris
split junco
#

Yup.

heady iris
#

note that this isn't going to cause Unity to submit the request multiple times

#

also, that's not what you're using

#

this is talking about the obsolete WWW class

dawn nebula
#

Seems to hang at the top of the arc too.

heady iris
split junco
#
using (UnityWebRequest www = UnityWebRequest.Post(url, form))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("Error: " + www.error);
            }
            else
            {
                Debug.Log("Form upload complete!");
            }
        }

This fixed the issue.

heady iris
#

i don't think it did anything

#

you should verify this by testing it again with the original code

#

It is the correct thing to do, mind you

#

I just don't think it caused multiple requests.

vale prairie
#

This error is output when a host a client tries to connect to a host. The client receives data fine but cannot send data nor perform any actions.
Trying to send ClientConnectedMessage to client 0 which is not in a connected state.
Reply pings would be much appreciated ‼️

rigid island
#

watch the video at .2x speed if it helps

#

its just very well done to not look as simple, but it really is simple

dawn nebula
split junco
heady iris
#

Did you change the "Enter Play Mode" options?

#

e.g. turning off Domain Reload

rigid island
split junco
#

No. I have no idea what that is.

heady iris
#

the second time you entered play mode?

split junco
#

Yes.

dawn nebula
heady iris
rigid island
heady iris
#

I see this in Unity 6. It's a set of checkboxes in older versions.

split junco
#

I ran once, clicked "finish" which triggers the script pasted above. Then I quit the playmode and entered the playmode again.

dawn nebula
#

Oh 100%, but just being able to take some 0-1 range and remap it however you want is so incredibly powerful.

heady iris
#

give me Blender's graph editor

rigid island
#

gonna try it, Hmm its open source, if I knew anything of c++ I'd try to steal the code for it

heady iris
#

blender lets you manipulate your keyframes much like you can manipulate objects in 3D space

#

you can move and scale them around various origin points

knotty sun
heady iris
#

you can even rotate them, if you so desire

rigid island
heady iris
#

Blender is mostly C++ with Python for extensions

rigid island
knotty sun
#

graph stuff is an extension iirc

heady iris
#

you can define new graph node types in Python, but you can't really make them do anything

#

I was just looking at this a day or two ago. It's understandable given the...performance characteristics at play

split junco
heady iris
#

probably a double-click

dawn nebula
#

@rigid island Considering I need to path the change based on the start and end target, do you think it would make sense to define the shape of the spline from a 0-1 range across all 3 axes, and then scale it along the vector between the start and end point?

rigid island
#

@dawn nebula if you're looking to do the same thing , I would lerp the start and end pos dynamic, the "mid section" is the same flip animation/spline anim

past leaf
past leaf
#

cheers

gritty lily
#

Hi! I've been working on a state system, and I've hit a bump in the road. My idea was to store the states in a dictionary to reduce the amount of variables in the code. However, I'm now facing a challenge - I'd like to allow for easy drag-and-drop functionality for state scripts into an array within the Unity editor. Any suggestions on how to do it?

narrow summit
gritty lily
#

Can it enable dragging one interface object into a list in the Unity inspector? I use both an interface object and a key for each state

#

of what I've read it doesn't seem to be possible without a gameobject but asking in here anyways as I might have missed something

heady iris
#

I don't know what you mean by "interface object"

#

Do you mean a MonoBehaviour that also implements an interface?

chrome trail
#

So is there a way for me to check for all vertices in a mesh within range of an arbitrary point that is faster than cycling through each and every vertex and measuring distance?

dawn nebula
#

@rigid island Unity's spline package seems to cause a stackoverflow every time I click a knot, breaking the editor.

#

πŸ™ƒ

#

Yep every single time.

#

Wow

rigid island
dawn nebula
#

Spline 2.6.1
Unity version 2022.3.27f1

rigid island
#

you tried restart before?

dawn nebula
somber nacelle
#

reproduce that in an empty project and submit a bug report

dawn nebula
gritty lily
rigid island
heady iris
dawn nebula
gritty lily
rigid island
#

idk how to do it now, unless you use manifest i suppose

dawn nebula
heady iris
gritty lily
#

I will give it a try seems promising

heady iris
#

yeah, see

rigid island
heady iris
#
using UnityEngine;

public class MyPoco : IMyInterface
{
    /// <inheritdoc />
    public void Greet()
    {
        Debug.Log("Hello, World! I'm MyPoco");
    }
}
#

this example

gritty lily
#

So I can drop raw scripts in with this plugin?

heady iris
#

well, you can serialize instances of classes with it

gritty lily
#

If I understand this lane writes you can: "Classes (custom classes that implement said interface)"

heady iris
#

You can already do this if you don't need to allow for polymorphism

gritty lily
#

So if I have implemented a class with this plugin the script will be an option to put in the inspector

heady iris
#
[System.Serializable]
public class Stuff {
  public int foo;
  public char bar;
}
#

you can serialize a Stuff field just fine

heady iris
gritty lily
#

What I try to do is to have a state manager and a base state(which is a raw interface) I don't want to create a class to wrap the interface. Then my plan is to do a state system with a dictionary that contains the states, so I easily can swap state implementations and change references to states

fringe scroll
#

I'm having an issue with my Assembly Definition for code in an Editor folder for a custom package I have created. Everything else works for my runtime assembly definition. But the editorone doesn't let me access anything in the UnityEditor assembly. Am I doing something wrong or is this a bug?

leaden ice
fringe scroll
#

That shouldn't affect me calling stuff from UnityEditor should it?

#

Becasue I have the other assembly definitions set up and they have the correct depencencies.

leaden ice
#

Or wait I think I misread. Show the inspector for the asmdef?

fringe scroll
leaden ice
#

You excluded the editor platform

fringe scroll
#

Splines.Runtime has the SplineEventSelectorData class in it and it should work

#

πŸ€”

#

let me try changing that

leaden ice
#

I think you did at least that tooltip is blocking things hehe

#

You probably want the opposite

#

You want ONLY Editor

heady iris
#

yea, scroll down

#

oh wait, you don't toggle between "exclude" and "include"

#

you just check everything except Editor

#

(but there is a "select all" button at the bottom!)

leaden ice
#

Or uncheck the Any Platform thing

#

And only check editor as included

fringe scroll
#

OH ok hold on let me see if that works for me.

dawn nebula
#

Brutal.

somber nacelle
#

!bug report time!

tawny elkBOT
#

πŸͺ² To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

πŸ“ If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click β€˜Report a problem on this page’!

πŸ’‘If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

fringe scroll
#

Oh ok that fixed it

fringe scroll
heady iris
fringe scroll
dawn nebula
somber nacelle
#

yeah unlucky for you, but lucky for everyone else you found a bug in that version so it can (hopefully) be fixed quickly lol

dawn nebula
dawn nebula
#

And that's from April

dawn nebula
#

What... is going on.

#

This is an empty 3D URP template project.

latent latch
#

time for unity 6

sterile reef
#
public void GenerateGrid(CellInfoDatabase database)
 {
     
     for (int y = 0; y < gridSize.y; y++)
     {
         for (int x  = 0; x < gridSize.x; x++)
         {
             GameObject tile = GameObject.CreatePrimitive(PrimitiveType.Plane);
             tile.GetComponent<MeshFilter>().mesh = meshRef;
             tile.GetComponent<MeshCollider>().sharedMesh = meshRef;
             tile.name = $"Hex_{x}_{y}";
             tile.transform.position = GetPositionForHexFromCoordinte(new Vector2Int(x, y));

             tile.transform.SetParent(parent, true);

             TileInfo cellInfo = new TileInfo();
             cellInfo.LocalName = tile.name;
             cellInfo.CurrentColor = Color.green;
             cellInfo.ID = new Vector2Int(x, y);

             database.CellInfos.Add(new Vector2Int(x,y), cellInfo);
         }
     }
 }
 public Vector3 GetPositionForHexFromCoordinte(Vector2Int coordinate)
 {
     int column = coordinate.x;
     int row = coordinate.y;
     float width;
     float height;
     float xPos;
     float yPos;
     bool shouldOffset;
     float horizontalDistance;
     float verticalDistance;
    float offset; float size = outerSize;
     if(!isFlatTop)
     {
         shouldOffset = row % 2 == 0;
         height = 2 * size;
         width = Mathf.Sqrt(3) * size;
         
         horizontalDistance = width;
         verticalDistance = height * 0.75f;

         offset = (shouldOffset) ? width/2 : 0;

         xPos =(column * (horizontalDistance)) + offset;
         yPos = (row + verticalDistance);

        
     }
     else
     { 
         shouldOffset = column % 2 == 0;
         width = Mathf.Sqrt(3) * size;
         height = 2 * size;
        
         horizontalDistance = width * 0.75f;
         verticalDistance = height;

         offset = (shouldOffset) ? height / 2 : 0;

         xPos = (column * (horizontalDistance));
         yPos = (row * verticalDistance) - offset;
     }

     return new Vector3(xPos, 0, -yPos);
 }
#

any reason why it generates the grid this way?

#

i read the docs and followed a guide

latent latch
#

something to do with your code and math I would assume

sterile reef
#

yeah

#

tho

#

i cant see where

grave thorn
#

Hi, so I have an animation event which is sitting on the animator of a gameObject called "EnemyBody".. this enemy body is the the child of the 'Enemy' gameObject, there is a function in the script which sits on the 'Enemy' gameobject, I need to access this functon from the animation event mentioned previously.

dawn nebula
#

Alright well time to download Unity 2022.3.16f1

#

And if this doesn't work.

#

I don't even know...

cosmic rain
sterile reef
cosmic rain
#

Oh, it's supposed to be when it's flat top.

#

Debug your code then. Make sure you're not going the flat top path when it's not.

leaden ice
#

And the overlap has z-fighting

sterile reef
#

that cant be it cuase there is room between the hexes

#

oh

#

i got it

#

yPos = (row + verticalDistance); >> yPos = (row * verticalDistance);

#

smh my head

dawn nebula
#

It might be doomed.

#

Does this package even work >_>

#

has it ever worked?

#

has anything ever worked πŸ˜”

somber nacelle
#

2.5.2 worked perfectly fine for me on 2023.2.9 when i used it for a jam in february

dawn nebula
#

Then I click around the knots and boom crash.

#

Spline doesn't even need to be closed.

vagrant blade
#

I've seen the spline package crashing recently as well. I switched to the free Dreamteck spline package on the asset store.

dawn nebula
#

I've jumped across multiple Unity versions, multiple Spline versions.

#

All the same result, all on an empty URP Template.

#

On versions that others have said worked for them.

vagrant blade
#

Maybe, I hadn't looked into it myself. Just switched lol

dawn nebula
#

Is Dreamteck good?

vagrant blade
#

Yep

dawn nebula
vagrant blade
#

I think so

dawn nebula
#

We ride then.

dawn nebula
#

Ty

sterile marten
#

Has anyone else had issues with transform.rotation.eulerAngles only returning a y value? The transform is rotating on the x axis, so I don't know why that is returning as 0

dawn nebula
#

It doesn't seem to be cleaning up its children when nodes are deleted.

sterile marten
#

okay, Unity is refusing to give me the x value of a euler local rotation that I can prove without has a non-zero x value

quartz folio
sterile marten
#

I have a script explicitly changing the x rotation of that transform

quartz folio
#

You'll have to post some code then

sterile marten
#

The first image is defining the rotation of the transform every time the player moves their mouse.

The second has the first debug log reporting that transform's rotation

#

They are both referencing the same Object

#

zRotation == aimParent

#

I have a theory as to why these are different

#

theory proven wrong

#

Also getting a zero for the x value of any transform rotation that I reference with that variable

#

anything that isn't ultimately parented to my PlayerCharacter has this same missing X value. I have heard that a rigidbody may cause these problems, but that makes me wonder what is causing my movement to still work

somber nacelle
#

are you perhaps referencing prefabs on the object that is returning 0 for the x axis?

sterile marten
#

no prefabs

#

well, there is a prefab that has the same parent, but I don't see what that has to do with it

grave thorn
#

Hi, so i have this gameobject, i flip it using its scale when it hits a wall.. there is a child of this gameobject, I dont want the child to flip, any ideas?

spring creek
grave thorn
#

yes dis is 2d

grave thorn
#

i dont really care what i use to flip it.. its just that i dont want the child to flip

spring creek
#

It's a bool as you can see in the docs.
Set it true and false

grave thorn
#

got it

#

wait no this doesnt work

#

bc its not a sprite

#

its a gameobject

#

with boxcolliders and stuff in it

#

how do i combat the problem of only the parent flippng and not the child

#

ok i solved it on my own.. for anyone wondering how to flip a parent without flipping the child..

  1. Flip the parent
  2. Flip the child

this unflips the child while the parent remains flipped

spring creek
#

What does it have, a sprite renderer or a mesh renderer?

grave thorn
#

none of those

#

its jut a boxcolider and a script

grave thorn
spring creek
grave thorn
#

its a child called "EnemyBody"

#

its not in the parent

spring creek
#

Instead of just changing the direction of movement I mean

grave thorn
#

ok so heres the exact hieracy:
Parent: Enemy
Childs: HealthBar, EnemyBody

I need the Enemy (the colliders on it) and the Enemy Body to flip while the HealthBar stays in the same direction

spring creek
#

The enemybody could have used it though, if it was just visual

dusk apex
#

If this is 3d, forward would be the direction you're facing where y would be a value relative to your forward direction in the y axis.

sterile marten
#

because its pointed upward

quartz folio
#

Can you screenshot that object with pivot mode set to local?

#

Because transform.forward will 100% not do that, so something must be wrong with your setup or code logic

spring creek
#

You cropped out the hierarchy and inspector

full canopy
#

anyone know why the movetowards line does absolutely nothing to the position?

{
    transform.parent = primaryGrabbingObject.transform;
    transform.localPosition = Vector3.zero;
    transform.localRotation = Quaternion.identity;
    transform.position = Vector3.MoveTowards(primaryGrabPoint.position, primaryGrabbingObject.transform.position, Mathf.Infinity);

    rigidbody.isKinematic = true;
    Debug.Log("prim hand only");
}```
#

primaryGrabPoint and primaryGrabbingObject are at totally different positions btw, its just not moving the position for whatever reason

spring creek
#

Also, have you logged the two positions, and result of movetowards?

full canopy
#

in order, primarygrabpoint.position, primarygrabbingobject.position, and the movetowards result (yes calculated before its actually moved)

#

however the transform's local position remains at 0 (well, relatively zero. as close to zero as floats get)

#

the movetowards result is expectedly working

spring creek
#

So they are at the same position.

full canopy
#

its just not getting moved to where it needs to go for some reason

spring creek
#

Oh, alright

#

Well, where does it need to go?

full canopy
#

and i used mathf.infinity temporarily because making the step be the distance didnt work either lol

spring creek
#

You are trying to move it to where it already is

full canopy
#

how so?

#

the thing being moved is not the primary grab point

spring creek
#

Ah, well log the thing being moved of course...

full canopy
#

alright 1s

spring creek
#

But your first parameter of MoveTowards is wrong though

#

First param and second are at the same position.

full canopy
#

im trying to move a parent so that a child is at another objects position

#

first param and second are not though as can be seen by the log

spring creek
#

The log shows the same position three times

full canopy
#

no the first is different

spring creek
#

Barely

full canopy
#

im in vr so small number changes are rather large

#

just spacially

#

sorry not in good focus rn

#

im all brain fogged and this really simple issue is plaguing me lol

spring creek
#

The first param should be transform.position, as shown in the example code

full canopy
#

oh true

#

i guess movetowards is not the method i should be using

#

originally i had just done
transform.position += (primaryGrabbingObject.transform.position - primaryGrabPoint.position);

#

but that was different each time i grabbed it

#

oddly inconsistent and i dont know why

spring creek
#

That just adds the directional vector between those two objects. That doesn't seem like what you want either

full canopy
#

ok let me explain a lil further

#

transform is the parent object here. it has primarygrabpoint as a child
the grabbingobject is separate. I want to move the parent so that primarygrabpoint is at grabbingobject.

#

what if i calculate the offset between grabpoint and the parent at start, then after i set the parent to be equal to the grabbing object, move it inverse to that offset

#

the primary grab point never moves, and i doubt ill ever need that functionality anyways

spring creek
#

Then getting that directional vector seems right. Then move in that direction until the distance between the child and desired point is near 0?
I do not do vr at all, so it does sound like that is part of the complexity here

#
Vector3 desiredDirection = (primaryGrabbingObject.transform.position - primaryGrabPoint.position).normalized;
grave thorn
#

Hi, I have a bullet that goes out from an enemy gun and when it hits the player i want it to damae the player.. the problem is that the player has 2 colliders, a circle2D and a box2D.. so when the bullet hits, it does double the damage, how do i make it only do damage when it hits the boxCollider2D and ignore when it hits the CircleCollider2D

#

The damage logic is on the bullet script btw

full canopy
#

unless you need the bullet to pass through the player, id just destroy it when it hits something

grave thorn
#

yeah it does get destroyed but it does 2x the damage.. cuz the player has 2 colliders

full canopy
#

how is it colliding twice if it gets destroyed then?

#

wait is it a projectile or a hitscan object?

grave thorn
#
void OnTriggerEnter2D(Collider2D hitInfo)
    {
        Destroy(this.gameObject);
        
        if (hitInfo.GetComponent<HealthBar>() != null)
        {
            playerHealth = hitInfo.GetComponent<HealthBar>();
        }

        if (playerHealth != null)
        {   
            if (playerHealth.currentHealth >= 0)
            {
                playerHealth.Damage(bulletDamage);
            }
        }
    }
#

here is the code for the damage

grave thorn
spring creek
spring creek
#

Oh, the bullet?

grave thorn
#

yes

spring creek
#

Why two colliders on the player?

grave thorn
#

cuz when i crouch i disable the top one (box col) and the circle col as the feet makes it easier to go up gradients

full canopy
#

wait is this 2d or 3d?

grave thorn
#

2d

full canopy
#

ok just making sure lol

grave thorn
#

lmao yeah

spring creek
#

Ok. Not the greatest way to do that.
But simple fix, on the bullet script make a bool called hit. In OnTriggerEnter, do an early return if hit is true

#

Destroy isn't immediate, so the bool will be an immediate way to prevent it from running again

grave thorn
#

tbf i can just make the player take 1/2 the damage but thats a very botchy way and i dont wanna do that

full canopy
#

def dont do that

grave thorn
full canopy
#

basically return before the rest of the code is executed

grave thorn
#

ok ill try the bool thing

spring creek
grave thorn
#

ah got it

#

ill try that

full canopy
#

also makes it easier if you want bullets to go through the player in the future

grave thorn
#

for that i just make a layer and make it so that that layer cant collide through the collision matrix

#

wohoo it worked!

#

thx so much @full canopy and @spring creek

full canopy
#

nice

#

yw

grave thorn
#

ya'll epic

full canopy
#

:)

#

@spring creek this method finally worked

{
    transform.parent = primaryGrabbingObject.transform;
    transform.localRotation = Quaternion.identity;
    transform.localPosition = Vector3.zero;

    offset = transform.position - primaryGrabPoint.position;
    transform.position += offset;

    rigidbody.isKinematic = true;
}```
spring creek
#

Nice! Glad you got it

full canopy
#

i think some things were just executed out of order and me not understanding they changed each other because it all happens in one frame

grave thorn
#

I have this piece of code that starts the enemy shooting and animation:

if (cooldownTimer >= attackCooldown)
                {
                    // Attack
                    cooldownTimer = 0;
                    anim.SetTrigger("rangedAttack");
                }

There is an animation event in the animation which calls this function

void RangedAttack()
    {
        enemy.RangedAttack();
    }

Then it calls the enemy.RangedAttack(); which is this function:

public void RangedAttack()
    {
        cooldownTimer = 0;

        // Shoot Projectile
        GameObject bullet = Instantiate(bulletPrefab, firePoint.transform.position, firePoint.transform.rotation);
        Debug.Log("Instantiated Bullet");
        bullet.GetComponent<EnemyBullet>().bulletDamage = projectileDamage;
    }

Now the problem is that the enemy should shoot based on the cooldown timer, but its constantly shooting regardless of the cooldown time.. any guesses as to waht the problem is?

cosmic rain
dusk apex
#

Or possibly that attack cooldown is zero. Where does the cooldown timer accumulate?

grave thorn
grave thorn
dusk apex
#

Maybe log the values and see if the if statement is true

#

If the if statement isn't true but it continues to fire, you can remove the if statement from your list of possible culprits.

grave thorn
#

I did a botchy job and its fixed.. good enuf for the dedline tmmrw lmaoo

remote tapir
#

how do I print

grave thorn
#

Another problem... I used this piece of code to move the bullet, its in the Update method of the bullet script.. idk where i got this from but i have no clue why its transform.right, i want it to be whatever direction the enemy is facing

rb.velocity = transform.right * speed;
grave thorn
remote tapir
spring creek
# remote tapir

What does the error say? This is cropped so much it is basically useless to show

#

I am guessing it is not in a method?

remote tapir
spring creek
#

Yep, not in a method

grave thorn
remote tapir
#

wtf is a method

grave thorn
#

a start or update or any other method

spring creek
tawny elkBOT
#

:teacher: Unity Learn β†—

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

spring creek
#

and check out w3schools

#

You need to know c# before beginning unity

grave thorn
spring creek
#

Log() is a method though, btw

#

the things that end in () are methods

remote tapir
#

i skip

#

i am super jenius 🧠

#

very smart

#

also why is it not printing still

grave thorn
#

it is

#

just once

spring creek
#

Likely not attached to a gameobject, or logs are hidden

grave thorn
#

wait is ur script on a gameobject

rigid island
#

scriptname doesnt match the class name, it wouldn't let you attach since they don't match

remote tapir
#

cant see anything in my console

remote tapir
#

i just created it in assets

spring creek
tawny elkBOT
#

:teacher: Unity Learn β†—

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

grave thorn
rigid island
spring creek
#

this is not a place for spoonfeeding and handholding

rigid island
#

its not even part of the scene

spring creek
remote tapir
spring creek
grave thorn
rigid island
remote tapir
#

ok i finally got to print hello world

grave thorn
#

LMFAOOO

remote tapir
#

i am so good πŸ‘

grave thorn
#

fr fr

remote tapir
spring creek
#

Yes

remote tapir
#

what exactly is considered "loaded"

rigid island
#

unity is component based, any component must be on a gameobject to run

spring creek
remote tapir
#

for how everything works

#

and loads

spring creek
#

I have linked the lessons twice

remote tapir
#

what is a scene, what makes a scene "active",

#

how to deactivate scene

#

etc etc

#

!learn

tawny elkBOT
#

:teacher: Unity Learn β†—

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

rigid island
#

!docs

tawny elkBOT
rigid island
#

also this

remote tapir
#

which do I press first

spring creek
spring creek
rigid island
spring creek
#

then do junior programmer

remote tapir
#

everyhting I need to know and in-depth explanation on how scripts load, etc is in there?

#

once the language barrier is gone i should be able to do anything i want

rigid island
#

learn and the manual

spring creek
rigid island
#

learn gives you the hands on experience and teaching, manual if you want to learn how everything works behind scenes

#

API is for the methods/classes that are included (scripting wise)

spring creek
#

game dev is one of the most complex and difficult types of software development out there. Be prepared for a struggle
You need to spend a lot of time learning, and finishing even ALL the unity lessons will not be enough

grave thorn
#

ok so when the bullet is spawned in, it goes through this

void Start()
    {
        rb.velocity = transform.right * speed;
    }

but the thing is it always points to the right and shoots to the right, even when the shooter is facing left.. how do i change that? btw i change the direction of the shooter by putting a '-' infront of its local scale

lean sail
grave thorn
#

yeah im not rotating im just inverting the scale

rigid sleet
#

AKA always goes to the right

#

you gotta make it point to your actual intended forward

grave thorn
#

Its fine i solved it.. i remade my flipping machanics to rotate instead of invert scale and that seems to have solved it

winter charm
#

So I am designing first person puzzle game, and I got stuck. So currenctly I have two interfaces with two types od items, ICollectable and IInteractable. I get them off item with raycast and invoke methods in it. How could I make this all one? Collectable hold different variables than interactable would ever need. Do I just have a Collect and Drop method in my PlayerController script? Or how would I manage this the best way?

grave thorn
#

Thx tho

winter charm
lean sail
#

If you're not really using these anywhere else, itll work fine

keen skiff
#

hi am new here
making a dockerfile for the first time to try run my project headlessly through linux but i keep getting this message
assistance would be very much appreciated

winter charm
winter charm
lean sail
winter charm
#

I think that I am just really stuck looking in one direction, and cant get out of it.

#

Should I just have collect and drop on PlayerController?

lean sail
#

actually holding the item in hand would just be a matter of moving it to the players hand and possibly making it kinematic, whatever holding means in your game.

winter charm
lean sail
#

its not really the approach id want to go with, because im not a fan of having to check every possible derived type especially if this gets way more complex. But if this is simple enough you can get away with it

full canopy
#

anyone here familiar with the unity xr interaction system? I just need to be able to get the gameobject that is interacting with any of the xr derivatives of the xrbaseinteractable. specifically, the xr grab interactable and xr simple interactable

full canopy
#

i did not know there were channels for vr

winter charm
plucky inlet
#

But from your question, you should just check the type (or preferably an enum?) and send the component from your input to your player. Player checks for availability of slot and current item and then feedbacks to the component, if it gets picked up or collected or whatever you are doing with your interfaces.

#

It just feels like you are branching out too much on those interfaces

lean sail
# winter charm What approach would you choose then.

first thing is i would probably try to stay with IInteractable, because you are just interacting with the object whether its being collected or not. theres a lot that depends on your exact setup so its hard for me to suggest much more. Like one thing for pure simplicity could be just adding a OnInteractionEnd method which your collectable could implement so it can be dropped. Anything else can just do nothing with it. Not really the best pattern wise but that same could be said about needing to cast to check for every single derived interface.

plucky inlet
#

I agree with bawsi. Keep it simple, an item can be picked up, can be used, can be consumed, can be equipped or what not. whatever happens on those methods can then be directed by an enum you set for each item for example. As soon as it gets out of logic and into metadata for each item, it should not stay within your code cause you gonna find yourself branching even more into weird spaghetti code to cover all of your needs just from code.

lean sail
#

if you wanna see some fat garbage, this is how i handle effects (do X when Y happens), a similar approach to what i said above except with abstract class. Derived classes can implement these methods if they want. I have an enum which is used to say if these methods should be called.
Im not proud of it, yea itll log an error if i choose the wrong enum which is easy to do, but its so simple and works well.

#

I would take this in my own project any day over

if(obj is A)
....
if(obj is B)
...
// and more when more functionality is introduced
winter charm
winter charm
# plucky inlet I agree with bawsi. Keep it simple, an item can be picked up, can be used, can b...

So if I understand you right I could make an enum in InteractableItem base which would be for now either Activatable or Collectable then we implement the IInteractable interface method Interact where we check for what item it is e(num type). Then we would define virtual void for each item. After that we create two derived classes ActivatableItem and Collectable Item and here I would override?

plucky inlet
winter charm
plucky inlet
#

Just be careful about scriptable objects being reset after every new app start

winter charm
plucky inlet
#

No, it gets reset. You can store the state as a serialised object to json and on appload, load those json files and overwrite your default state. But the scriptableobject itself will ALWAYS reset when you restart the app/game. Just do not get confused by the editor, because in the editor, it just changes it and does not reset.

winter charm
plucky inlet
# winter charm Alright but the approach would be good?

It depends on your setup, but yes. If you add items which would need more than just an enum, you could also just create "Tags" and add tags to the list of the item. But with my approaches, I always target the item data to be derived from a database or a list of predefined items (via SO or whatever). the code is just there for handling. You do not want to inherit "Apple Item" from Item class as its own class. Apple Item would be type of Item with the metadata name Apple for example.

winter charm
#

Just searching for best solutioms that i can learn from.

plucky inlet
fair rivet
#

Hi, I am planing to crate a game with some terrain, I have been researching and I kind of like the terrain tool approach that the official unity terrain tools extensions offer

The think is that I would like to generate the noise and terrain at runtime using the noise generator and the terrain toolbox but I can't find a way to do that, any advice?

fleet gorge
#

modify terrain data
you may need to rebake terrain collision which I'm not sure how it works

#

one sec

#

oh it's binary

golden sinew
#

for some reason, i can't access to hinge joint component of object hit by ray

#

its an fps game

#

the script is attached to the camera

#

im trying to make physically pushable door

#

that mouselookscript.sensX/sensY = 0 is just to disable camera movement while using/opening door

#

maybe something is wrong here?

fleet gorge
#

Wdym can't access it?

#

Like is hinge joint null when you use getcomponent?

golden sinew
#

no, like i can't change the value of target velocity

fleet gorge
#

to clarify, when you set target velocity to a value does it automatically get set back to 0?

golden sinew
#

yeah

fleet gorge
#

I read that it's a temporary variable. Look into how target force works instead. You can apply an angular force until you reach the desired velocity

#

If you're making a physically pushable door why would you need to set the target velocity?

fleet gorge
#

as in what are you trying to do?

#

if youre making an animation you can honestly hardcode the animation

golden sinew
#

no i meant codewise

#

i don't really know animation side

fleet gorge
#

rigidbody apply angular force

golden sinew
#

hmm but wouldn't door just rotate around itself?

#

cause i don't think you can change pivot point of an object right?

fleet gorge
#

you can make the mesh a child object

#

or use transform.rotatearound

golden sinew
#

ohh

#

okay

#

thanks

rigid island
#

But generally is easier to just make it child of another with correct offset and rotate parent

golden sinew
rigid island
#

personally would make sure my pivot is correct by using another object instead of rotate around

golden sinew
#

hmmm okay

fleet gorge
#

I'm making a rhythm game where users can create/share beatmaps. inside the beatmap file is a link to the song's audio which will be downloaded for the user and played as part of the level.

are there any security risks behind this?

chilly surge
#

Not inherently.

#

But you might have a pretty hard time loading dynamic audio.

heady iris
#

Unless someone finds a hilarious bug in the MP3/Vorbis/etc. decoder, no

#

But it could be used to be obnoxious

#

like distributing files that get flagged as malware

#

or downloading 100 gigabytes of garbage

rigid island
#

uneless the audio is CC or Public domain it is also piracy in a way

heady iris
#

the legal angle is more problematic :p

fleet gorge
#

This is more of a proof of concept, when the time comes I'll pull off a geometry dash and restrict it to newgrounds downloads

#

I'll still need to tackle the problem of loading sounds at runtime though

rigid island
#

oh ok if its testing purposes i would still use royalty free musics

fleet gorge
#

iirc everything on newgrounds is πŸ‘ to use

rigid island
heady iris
#

streaming assets is just a way to copy files into your build folder

#

If you need to load audio at runtime, you just need a way to decode compressed audio

#

Unity has a way to do that through a web request, actually

rigid island
#

maybe Fmod?

chilly surge
#

For loading dynamic audio, the only Unity way is to use UnityWebRequestMultimedia.GetAudioClip, since Unity does not expose its decoding, and the decoding it comes with is extremely limited.
Chances are if you allow user generated content, you have no choice but to either convert their audio at the time of uploading, or convert when you play them.

heady iris
#

it's weird how it's only exposed through this one method, yeah

#

but you can almost certainly grab a C# library to do this

#

especially since you don't need super low-latency decoding or anything

#

you can just decode an entire song

rigid island
#

naudio! is goat

#

prob overkill here actually

chilly surge
#

I needed to do something similar and I ended up just embedding FFmpeg.

heady iris
#

lmao

#

forget Java

#

ffmpeg runs on 56 billion devices

chilly surge
#

It's a different story if you are making a rhythm game for PC, but for mobile the Unity's audio has unbearable latency, and I wrote my own audio engine for that.

heady iris
#

fmod also has remarkably high latency by default, weirdly

#

i had to go turn down the buffer size by half (still works great)

#

it was really obvious

chilly surge
#

Yep, because low buffer size can cause buffer underrun which results in audio sounding like it's tearing/glitching, so I wouldn't be surprised if the default is set to so high to be on the safe side.

heady iris
#

yep

#

halving it again was too far

chilly surge
#

Tbf for most games audio latency being 100 ms isn't much of an issue, it's mostly a problem specific to rhythm game genre. If you are lucky to get by with Unity/FMOD that's great, otherwise you almost always need to go down a rabbit hole of audio solutions, or even making your own.

heady iris
#

it was more like 200ms lol

#

wait, that number is way off lol

#

the total buffer length is about 41ms by default

but I was having massive problems with audio latency before I changed the buffer size

#

and i'm not experiencing that now (after putting the size back to the default)

#

wack

#

time to investigate that

#

the default buffer length was 512, and I had turned it down to 256

golden sinew
rigid island
golden sinew
heavy gust
#

Hi, I have a prefab with a grid+tilemap and am trying to use the tilemap within the prefab in an edit-mode script.

Script: https://hastebin.skyra.pw/leqarudidi.csharp

This code instantiates a copy of the tilemap with the tiles in them, and they appear as children of the Tilemap component in the script. However, the tilemap itself seems to be empty. I'm also sure that I'm drawing to the correct tilemap.

rigid island
rigid island
#

also send current !code in a link

tawny elkBOT
rigid island
#

and show the scene view on how you setup the door, each gizmos shown

golden sinew
ionic tusk
ionic tusk
#

I dindt kknow wiich channel it fits my problem...sry...

rigid island
ionic tusk
#

should I use this one?

rigid island
#

just stick to one, doesn't matter which

#

if its a code question then it goes in A code channel

ionic tusk
#

ok

ionic tusk
rigid island
#

you see the reply its to them

golden sinew
#

where did i do wrong tho

rigid island
#

also * Time.deltaTime you should never multiply mouseInput by delta time

#

mouseInput is already framerate - independent

#

your door is setup wrong

#

you have to rotate the Parent not the child, make sure thats happening

ionic tusk
rigid island
ionic tusk
rigid island
#

I have no Idea why you are replying about someone else's issue

#

I'm literally helping @golden sinew

golden sinew
#

LOL

ionic tusk
#

yup know i see it so sry

rigid island
ionic tusk
#

yup sry about that to

golden sinew
rigid island
#

so be sure its parent

#

start from basics, work your way up the issue

golden sinew
#

hmm okay

rigid island
#

Debug.Log(b.name)

bitter prairie
#

Question:
I'm working on a stealth system where a capsule basically patrols an area and rotates. These work on a coroutine. We wanted to expand upon this and have it look towards and move towards the player once it's spotted them. When stopping the coroutine it teleports the patrolling capsule however. Anyone have any ideas on how to avoid the stopping of coroutines from affecting the patrolling capsules position?

rigid island
bitter prairie
#

I dont know it just does 😭

rigid island
#

then you have to post the !code

tawny elkBOT
somber nacelle
#

it sounds like you're just setting the new position instead of moving it to that new position

somber nacelle
#

that was not in response to your issue

golden sinew
#

XDD

rigid island
#

second time today lol

golden sinew
#

i fell into the trap as well lol

rigid island
#

its a busy morning

rigid island
#

doorObj.transform.parent.position * mouseX this to me looks wrong though

#

it would probably just be transform.up * speed

golden sinew
rigid island
#

ok

#

@golden sinew btw you dont need rb on the child, pretty sure the parent already makes child door collider as part of its rb

#

no reason why you can't put your own collider on root too and keep the mesh for visuals

golden sinew
#

transform.up broke all the code :/

rigid island
#

just use MoveRotation

golden sinew
#

yeah that looks like better option XD

rigid island
#

yeah idk torque makes sense for other stuff, this would not be it lo

golden sinew
#

oh gifs aren't allowed :((

fallow quartz
#

Is a bad practice using cds like this? Because if the game has been running for too long the float variable wont be able to save the value of Time.deltatime, isnt it?

somber nacelle
#

that condition doesn't make a whole lot of sense. are you sure you don't mean to be using Time.time instead?

fallow quartz
#

but still the question is the same

somber nacelle
#

but yes, around 2.7ish hours into the game, you may start experiencing more floating point inaccuracy issues with that as you lose precision

fallow quartz
#

so how would it be the best option to do this?

somber nacelle
#

that isn't to say that you absolutely will though

#

and using this method for cooldowns and timers and stuff is a perfectly valid option

knotty sun
golden sinew
#

but i used rotatearound instead

rigid island
hexed fjord
#

For some reason, my gyro control script is no longer working.
The player just looks at its feet. else is not triggering so there is gyro support.

    {
        rot = new Quaternion(0, 0, 1, 0);
        gyroEnabled = EnableGyro();
    }

    private bool EnableGyro()
    {
        if (SystemInfo.supportsGyroscope)
        {
            gyro = Input.gyro;
            gyro.enabled = true;
            return true;
        }
        return false;
    }

    private void Update()
    {
        if (gyroEnabled)
            transform.localRotation = gyro.attitude * rot;
        else
            transform.localEulerAngles = new Vector3(0, -90f, 0);
    }```
leaden ice
#

Is that Quaternion even valid?

rigid island
#

apparently its this Z : 180

rigid island
#

or is it maxing out at 180?

knotty sun
#

not sure but the rules of Quaternion math is w > 0 and <= 1

halcyon swan
#

Anyone good with laptop specs

rigid island
#

dang well you got me there, I know nothing of quaternion math. Ill stick to my eulers πŸ˜…

knotty sun
rigid island
#

haha Yeah mines been lost somewhere at some point

rigid island
#

a code channel is not a fit for that

heady iris
#

ah, of course: i can just copy a quaternion out of the inspector

#

indeed, a 180 degree Z rotation winds up producing [0,0,1,0]

heady iris
quiet depot
#

hey

open mulch
#

Why is it so hard to make games compatible with apples stupid self

rigid island
open mulch
#

iOS games

hushed locust
#

What is the difference between this type of documentation

// Explanation

And this type

/// <summary>
/// Explanation
/// </summary>
#

I read that the bottom is XML documentation but that doesn't give me much info

rigid island
open mulch
rigid island
bright widget
#

Hi guys im changing the value of the currentLevelForHUD through another script then this value goes to on enable missions.transform.GetChild(currentLevelForHUD).gameObject.SetActive(isActive); problem is currentLevelForHUD remains zero i have debugged the code the value is successfully being changed but in onenable its just remains zero
https://paste.ofcode.org/itT7PSKah2heFFBVQXx4FS

heavy gust
hushed locust
heavy gust
#

Keep it in a script. If you want, there's always tools for extracting documentation. Google "c# documentation tool"

#

But I don't see why you'd need that

rigid island
crisp flower
#

does anyone know if there's any way to filter or sort by filesize in the project window?

hushed locust
#

perfect, thanks πŸ™‚

crisp flower
#

I have no idea where is a more appropriate board to ask

#

you could probably code an extension πŸ˜›

#

I'm talking about the unity project window

rigid island
#

i think they edited

#

whatever

heavy gust
#

ah

#

didnt notice

crisp flower
#

so you can open for example every wav over 50mb to set certain inspector settings

hushed locust
crisp flower
#

chill out

#

πŸ™‚

rigid island
#

the unity project window is basic af

crisp flower
#

isn't it

spring creek
crisp flower
#

which is weird, maybe people here use extensions?

rigid island
#

the search feature might give you better result

#

idk any extensions

heavy gust
rigid island
#

ctrl + K

heavy gust
#

it gets tiring to talk with a filter

rigid island
#

the searchbar has a "query builder" , I bet you can find the one fore size etc.

crisp flower
#

I only saw in the docs label and type

#

but yeah I did wonder that

#

no wait

#

there is

crisp flower
#

thanks navarone you got me to it

rigid island
#

aye goodluck. You can only use bytes for filesize so gotta get a converter out

crisp flower
#

yeah hahah add zeros until it catches things

#

you can't multiselect to change properties on multiplies but it can at least help me to catch the obnoxious wavs that I need to load in background causing stutters

naive swallow
#

Okay, I need help designing/implementing an algorithm.

I have a series of non-uniformly shaped objects and I need to place them without overlapping on a tabletop. I've already got the object's bounding boxes calculated, and can position them on the table by the center point of their bounding boxes. So, we can think of it as "I have a series of rectangles of varying unknown sizes", and I need to position them inside of a larger rectangle of unknown size, one at a time, as they're spawned in. I don't have any particular needs to maximize the space between objects, so having one object in the far corner of the space is fine if that's what the algorithm would spit out.

I'd also like to add in an optional "padding" parameter that'd make sure the objects are no closer than a specified distance.

The naive way to do it is to start at X/Z corner of the table plus the extents of the first object, plus the padding, and then add the extents to the offset and recurse, but that would lead to less than optimal use of space. Consider this case, where we have the blue and red objects placed already, and try to place the purple one. Optimal space would put it above the blue box, adjacent to the reds, but the naive algorithm would put it flush with the bottom edge of the table, next to the blue box.

#

Oh God I just realized this is just the knapsack problem and it's NP Complete

#

I guess that's why I've been struggling to find an answer: there is none

leaden ice
#

Well, there's an answer

#

it's just not guaranteed to run in polynomial time

chilly surge
#

This is basically just texture packing, and there are plenty algorithms online for it.

late lion
#

Before that realization, I was going to suggest approaching this like building a spatial tree. When you add a rectangle onto the table, split the table into quads. To place an object, look for the smallest quad that can fit it and put it in there.

chilly surge
#

A very basic algorithm is:

  • Keeping a list of rectangles which represents available empty spaces.
  • The list obviously starts with just one rectangle of the entire space.
  • When trying to place a new item, find an empty space larger than the item.
  • Remove the empty space from the list.
  • Put the new item in the top right corner of the empty space.
  • Now the empty space has an L shaped unoccupied space.
  • Split that L into | and _.
  • Put | and _ into the available empty spaces list.
  • Repeat until all items are placed.
naive swallow
naive swallow
chilly surge
#

Yeah it doesn't matter which corner you put the item into the empty space, and it doesn't matter how you split the remaining L.

#

For texture packing, there are a lot of things you can do to optimize it, eg the orders of items, the orders of empty spaces, etc. But in your case seems like you don't need to care about any of that.

serene stag
#

Can we make changes into scene 2 from scene 1.

rigid island
#

ofc something like a singleton can interact with both and change stuff

serene stag
rigid island
#

you can probably put it in a DDOL

serene stag
#

What is ddol.

rigid island
#

its a special scene that lets you put objects that aren't affected by scene changes destroy

serene stag
#

I know ddol then. But

#

Ok will try.

#

I am making a portal from scene 1 to scene 2 and now I am able to see scene 2 from scene 1.

#

Ddol didn't came into my mind. Will try that.

patent parrot
#

Guys, how can I compare the value of an int with that of a list with different values ​​and if some are the same then return true

naive swallow
naive swallow
patent parrot
umbral fox
#

Is Application.persistentDataPath the correct x-platform path for writing a game's persistent data? Over the years, and on different platforms, I've seen/used lots of variations and hacks. Checking the docs today ... it looks like that path is broken at least on Linux (where it's a system-wide shared folder), most mainstream platforms it's a correct user+game specific folder, but notably mobile it appears to be a fallback folder that will only be correct for some (not all) API calls

serene stag
chilly surge
heady iris
heady iris
#

It's really ~/.config/unity3d/CompanyName/ProductName

#

so it works fine.

heady iris
serene stag
fallow obsidian
#

i cant seem to figure out why my ui items get messed up the 2nd time this ui pops up during runtime.
If I adjust the window size even by very little, it automatically fixes itself. If i enable and disable the canvas gameobject, it fixes and if i enable and disable the canvas scaler compoenent, it fixes. I'm not sure what's causing it though

First image is of it being bugged, 2nd image is me resizing the window and bringing it back to size of first image and it's fixed. Also an image for what the canvas looks like

waxen blade
#

I found some code to help me with vector comparisons, but I'm missing a package. It's offering 3 different ones for "Mathutil" which one do I need?

leaden ice
#

Use whichever one being used in whatever code you are copying or referencing

simple egret
#

(in this case that would be none of the 3 options anyway, since Unity does not support NuGet packages)

waxen blade
#

I wasn't sure if it was something commonly known or not, that's why I asked.

#

I realize now it's one of his own classes.

#

Sorry I asked.

simple egret
#

Should probably do as the first answerers did, which is by not using == to compare vectors. They're made of floats, which can suffer from precision issues

waxen blade
#

Yeah, I've been getting hit by them almost randomly.

#

I tried comparing the square magnitude instead but that also has the same issue sometimes.

simple egret
#

Consider constructing a direction vector from the two vectors to compare, and checking whether its magnitude is lower than some threshold

glacial halo
#

!code

tawny elkBOT
waxen blade
#
while (diff > .001)
{
//Move
}
diff = Mathf.Abs(foo.sqrMagnitude - bar.sqrMagnitude);

This is what I changed it to, but sometimes it says there's practically no difference even though the two objects are 1.5 units away, so it's very noticeable that it's not in the correct position. So I'm exploring more options.

glacial halo
#

Hey all,

Sooooo, having a brain thing.

    void PlayExplosion()
    {
        Debug.Log("Play Explosion");
        GameObject newExplosion = GameManager.Instance.enemyExplosionPool.GetPooledObject();

        ParticleSystem particleSystem = newExplosion.GetComponent<ParticleSystem>();

        Vector3 explosionLocation = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        newExplosion.transform.position = explosionLocation;
        particleSystem.Stop();
        particleSystem.Clear();
        newExplosion.SetActive(true);
        particleSystem.Play();
    }

Haven't use Shuriken in forever, so I'm not sure what I'm doing wrong. Everything here is working, except for 'resetting' the particle system back to 0 so that it plays from the beginning on 'spawn' from pool.

Anybody got any pointers please?

simple egret
umbral fox
umbral fox
# fallow obsidian i cant seem to figure out why my ui items get messed up the 2nd time this ui pop...

In my experience: canvas scaler is horribly buggy. A lot of Unity classes are badly written when it comes to scales and scaling (lots of places the authors 'forgot' that objects sometimes have scales other than 1/1/1). I avoid using it as much as possible.

Your case looks like your anchors are slightly wrong, I would check: are you configuring them from UI purely, or are you configuring them from code? If from code, you might not be handling the canvas scale values correctly

#

Adjusting the window triggers a full relayout of UnityUI which corrects a lot of the buggy UnityUI classes

fallow obsidian
#

the buttons and stuff are there statically so not generated/adjusted from code.

somber tapir
#

What's the correct approach to document two methods with the same name but different parameters? <inheritdoc> doesn't work because it takes the wrong one (since they have the same name). Should I just copy+paste the same summary from the first method?

leaden ice
#

I just duplicate it

waxen blade
heady iris
leaden ice
#

taking the magnitude of a point just tells you how far away from 0,0,0 it is

#

which we don't care about

simple egret
#

Meanwhile yours took the distance (magnitude) of the points themselves, which is the distance between the point and the world's origin (which is what a point is, the result of applying a vector to the world's origin)

fallow obsidian
heady iris
fallow obsidian
#

oh

heady iris
#

It would be displayed on the ContentSizeFitter's inspector.

fallow obsidian
#

isee what u mean

heady iris
#

If so, that's why you are having problems.

fallow obsidian
#

i dont have contentsizefitter components, dont think so... this is one of the buttons that was messed up

heady iris
heady iris
simple egret
heady iris
fallow obsidian
#

should it be affecting stuff even tho the object is disabled?

heady iris
#

No, and that's also fine

#

ContentSizeFitter is an issue when it has a parent with a layout group

#

you wind up with weird behavior as it fights with its parent

#

(it will display a warning when you do this)

fallow obsidian
#

aha i see

dusk apex
heady iris
#

your scroll view's Viewport doesn't have a layout group (because it's only job is to be a fixed-size region that masks the Content), so that works

heady iris
waxen blade
#

So now it'll look like this:

while (diff > .001)
{
//Move
diff = (bar - foo).magnitude;
}
#

Although I was checking for sqrMagntitude before. Am I going to have to change what the while loop is looking for if I switch from sqrMagnitude to magnitude?

heady iris
#

no, not really

#

To make it exactly the same, you'd just adjust the threshold you're comparing to

#

0.01 sqrMagntiude is 0.1 magnitude

#

but it'll be very close already

#

so, yes, but also no πŸ˜‰

waxen blade
#

Ha, okay. Magnitude should work then, thanks.

simple egret
#

sqrMagnitude is magnitude without the (not so expensive nowadays) square root applied internally

heady iris
#

It's marginally faster

#

You might as well use it if you're just comparing against a constant

waxen blade
#

It's working beautifully. Before objects would randomly get stuck if the floating points were barely tweaked, or if the game object movement speed was slow. Been fighting this for like 3 days.

cloud hedge
#
public static bool CancelAction()
{
    return Input.GetMouseButtonUp(0) || (Input.GetKeyDown(KeyCode.Tab) && (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt)));
}

I wanted to do something like this to "cancel" an action that involves pressing and holding, because currently if I alt tab out, the GetMouseButtonUp event doesn't fire. However, this still fails to return true when I hold alt then press tab. Any other idea for this?

leaden ice
cloud hedge
#

On losing focus will probably work for me, I'll try it

cloud hedge
glossy trench
#

!code

tawny elkBOT
magic harness
#

can anyone help me out on why this is happening?

#

how is this null

#

its a function that runs whenever a static action on another script is invoked

dusk apex
#

Maybe describe what you're trying to do and what's happening instead.

somber nacelle
magic harness
#

so... whenever an enemy dies, it calls a static function on another script( an Event bus) that fires an event and this is the part where i listen to get, get the data from the enemy to sum into my levelling system

somber nacelle
#

you need to make sure that whenever anything that subscribes to that event is destroyed it then unsubscribes from the event

magic harness
#

and whenever i debug this, the enemy gameobject still exists, but locals show me that the own object i am at is null

somber nacelle
#

otherwise you get NREs

magic harness
#

uhmmm okay

somber nacelle
#

and this is even more important if you've gone and turned off domain reloading

magic harness
#

yeah i get that, but i just checked all the references and im actually unsubscribing to it

#

i dont even destroy the object, its all pooled

somber nacelle
#

show the code where you subscribe and unsubscribe from the event

magic harness
#

here we go

#

and thats all

somber nacelle
#

okay well first, !code
second, where is that DisableInputs method called from

tawny elkBOT
magic harness
#

that object doesnt get disabled yet tho

somber nacelle
#

You'll need to use the debugger to figure out what isn't unsubscribing πŸ€·β€β™‚οΈ

cosmic rain
#

You subscribe in 3 places, but unsubscribe only in 2. It could be that some object is subscribed several times to the event

magic harness
#

Thanks guys, you pointed me in the right direction but it wasnt it.

The problem was that i was calling a function that was calling that event whenever i dealt damage, even when the enemy was already dead.

#

So i guess i have to check if an enemy is alive before actually killing it

cosmic rain
magic harness
#

yeah thanks for the help!

alpine harness
#

I just started messing around with the Splines package and I can't figure out how to access the additional properties of a Spline Container: Int Data, Float Data, Float4 Data, Object Data. Like, it looks like I should be able to name and access these Int Data properties but I can't find out how from the docs or from asking Unity Muse. Maybe y'all can point me in a direction? Here's my inspector.

wooden pawn
#

hey everyone! im making a game similar to omori / pokemon in the type that you explore an area until you run into a transition wall, where it takes you to another scene.
https://gdl.space/gekeguyato.cs
the difficulty im having is what to put in the very last else if statement, which will probably just call another script because it will be a lot of code. I want to know the best way to tell the SceneManager what scene to load based on where you are. my best ideas so far are to tag each loading zone with a different tag(will probably get tedious), or to have it detect what scene its on and then use only a couple of tags that describe where a general set of loading zones might be in a scene(north, south, east, west, house1, house2, cave1, you get the idea). it would use less tags but still be pretty repetitive. anything that uses tags will have to change the way the code checks the tile anyway. anyone have any insight that might be better?

#

the idea is that once the player tries to enter the white square(tagged "Transition") the raycast will see it and then call another script that manages which scene it will transition to

steady moat
# wooden pawn the idea is that once the player tries to enter the white square(tagged "Transit...

Use ScriptableObject to represent each individual scene instead of Tag. Something like (pseudo code, will not compile):

[CreateAssetMenu(...)]
public class SceneDefinition : ScriptableObject
{
  [SerializeField]
  //Use Addressable to manage scene
  private AssetReference sceneAssetReference ;

  public AssetReference SceneAssetReference => sceneAssetReference;
}

public class SceneLoadingTrigger : MonoBehavior
{ 
  [SerializeField]
  private SceneDefinition sceneDefinition;
  
  public void OnTriggerEnter2D(...)
  {
    GameFlowManager.Instance.LoadScene(sceneDefinition)
  }
}

public class GameFlowManager : MonoBehavior
{
  //Create a Singleton or us a pattern such as ServiceLocator
  ...
  private List<...> loadedScenes = new List<...>();  

  public void LoadScene(SceneDefinition sceneDefinition)
  {
    var handle = sceneDefinition.SceneAssetReference.LoadSceneAsync();
    loadedScenes.add(handle);
  }
}
wooden pawn
shell scarab
wooden pawn
leaden ice
shell scarab
shell scarab
wooden pawn
shell scarab
shell scarab
#

I wonder why they don't have any noise function that includes gradients or partial derivatives for perlin noise

wooden pawn
brazen hedge
#

when I add the vfx to the object, it does not show or work

brazen hedge
#

oh tnx

spring creek
#

I beleive they have pins there that can help

wooden pawn
#

I need some more help. Here's what I've got so far:
3 scripts: a SceneDefinition ScriptableObjectDefinition, a TransitionManager MonoBehavior, and a Player Monobehavior.
2 Scriptable Objects that coincide with 2 different scenes

What I want to happen:
The Player script detects that the player has tried to enter a Tile gameobject with the "Transition" tag. This calls the TransitionManager gameobject to transition the scene to the correct scene as defined by the ScriptableObject that has a string attached with the Scene Name that that specific gameobject will load to.

https://gdl.space/ofeqatitug.cs

The issues I ran into:
I have no idea how to reference the scriptable objects. this is what ive got so far. im really stuck

leaden ice
#

Direct serialized references in the inspector

molten moon
#

hey does anyone know how i can get momentum movement for my 3d unity game? im trying to make a game inspired like lethal company and love the movement. Any tips?

leaden ice
#

Use a Rigidbody

molten moon
wooden pawn
leaden ice
leaden ice
#

Like why one earth are you doing this?
FindObjectOfType<TransitionManager>()

#

You should be using the one your Raycast hit

wooden pawn
#

I'm not sure if thats possible

leaden ice
leaden ice
wooden pawn
#

How can i do that?

leaden ice
#

Ever heard of GetComponent?

wooden pawn
#

yes, but I couldnt find anything in it that would let me access a script components variable

leaden ice
#

Your code is literally already accessing the collider AND the GameObject

#

If you know about GetComponent, I'm not sure what you think you're missing here

#

E.g.

TransitionManager tm = hit.collider.GetComponent<TransitionManager>();```
wooden pawn
#

that gets the script but how do i get the variable from it?

leaden ice
#

Same way you get a variable on absolutely anything

#

With the . operator

#

But why do you need a variable?

#

You just need to call the function

wooden pawn
#

I can't just call the function unless its static

leaden ice
#

Wrong

leaden ice
wooden pawn
#

yes thats what ive been trying to do

#

thank you

leaden ice
#

tm.TransitionScene();

simple ruin
#

How do you fix this wierd striping issues of blocks in a voxel engine? They don't show up like this in the paused state so why is it happening during runtime

#

it happens in the built version of the game too
here's how im rendering textures and UVs

leaden ice
simple ruin
#

sorry, it's borrowed code

#

Is this what you're looking for?

#

because the entire chunk is 1 mesh

#
{
    int xCheck = Mathf.FloorToInt(pos.x);
    int yCheck = Mathf.FloorToInt(pos.y);
    int zCheck = Mathf.FloorToInt(pos.z);

    xCheck -= Mathf.FloorToInt(chunkObject.transform.position.x);
    zCheck -= Mathf.FloorToInt(chunkObject.transform.position.z);

    return voxelMap[xCheck, yCheck, zCheck];
}

void UpdateMeshData(Vector3 pos)
{
    byte blockID = voxelMap[(int)pos.x, (int)pos.y, (int)pos.z];

    bool isTransparent = world.blocktypes[blockID].isTransparent;

    for (int p = 0; p < 6; p++)
    {
        if (CheckVoxel(pos + VoxelData.faceChecks[p]))
        {
            vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 0]]);
            vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 1]]);
            vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 2]]);
            vertices.Add(pos + VoxelData.voxelVerts[VoxelData.voxelTris[p, 3]]);

            AddTexture(world.blocktypes[blockID].GetTextureID(p));

            if (!isTransparent)
            {
                triangles.Add(vertexIndex);
                triangles.Add(vertexIndex + 1);
                triangles.Add(vertexIndex + 2);
                triangles.Add(vertexIndex + 2);
                triangles.Add(vertexIndex + 1);
                triangles.Add(vertexIndex + 3);
            }
            else
            {
                transparentTriangles.Add(vertexIndex);
                transparentTriangles.Add(vertexIndex + 1);
                transparentTriangles.Add(vertexIndex + 2);
                transparentTriangles.Add(vertexIndex + 2);
                transparentTriangles.Add(vertexIndex + 1);
                transparentTriangles.Add(vertexIndex + 3);
            }
            vertexIndex += 4;
        }
    }
}```
#

this is the part that renders the triangles

molten moon
#

anyone know how to hide this raw image while editing game?

#

anyone

simple ruin
#

But I don't see anything that would potentially lead to inaccuracies like seen in the scene

rigid sleet
#

so when the manager initialzies, it saves a static reference to itself in the class, that way you can access it everywhere

leaden ice
#

You're talking about a Singleton, which this thing is not

rigid sleet
#

easiest way to implement singletons in Unity, and imo one of the best way to handle any kind of managers that dont need to know entirely about the game state (Like a music or SFX manager)

rigid sleet
#

or have that scriptable object reside on a singleton

#

I personally prefer having singleton managers that survive through the game loop instead of having these managers constantly create/destroy themselves

#

it also asure no race conditions or weird scene setup weirdness happens

wooden pawn
rigid sleet
#

that loads all of your managers that will not die and survive the entire game loop

#

public class SingletonManager : MonoBehavior {
    public static SingletonManager Instance;

    public void Start(){
      Instance = this;
    }
}

wooden pawn
#

the loading zones are gameobjects that ill put in each scene where the player has to walk to trigger it

rigid sleet
#

now you can access that singleton manager from everywhere with SingletonManager.Instance

wooden pawn
#

each one of those white tiles has a transition manager script

#

i tried to do it with a single empty gameobject that would manage it but i couldnt figure it out because it had to be a different SO for each area

rigid sleet
#

it seems to me you dont want to actually do that

wooden pawn
#

oh is what im doing better?

rigid sleet
#

like, instead of having to asign a SO to each area like that, it seems like you want an SO that holds references to all of your individual SOs

#

with a Dictionary or something similar

wooden pawn
#

or just something else to attach to each loading zone tile thats why originally i wanted to make a different tag for each scene

#

because i dont want to have so many scripts running but i guess it wouldnt matter because they dont do anything unless theyre hit by the raycast

#

and only one would be hit at a time

rigid sleet
wooden pawn
#

yeah but im not experienced enough to figure it out yet

#

im not sure what an Adddresssable is

#

i found it in the packages but i didnt figure out how to use it

rigid sleet
#

you can skip that and instead just work directly with an scene reference

wooden pawn
#

how do you make a scene reference?

#

or i guess just show me what youre thinking

rigid sleet
#

yeah one sec looking for a script example

#

hmm I dont have anything at hand

#

what I usually do is reference a scene by its build name and store that into a SO/Dictionary

#

and indirect that with a custom ID so it doesnt depend on path/names