#archived-code-general

1 messages · Page 100 of 1

sour zealot
#

im not a beginner

#

im just a beginner in this field

#

: )'

potent sleet
#

🙄 it's okay to admit limited knowledge so someone can better help according to that knowledge

sour zealot
#

can we move into code beginner?

#

and you help me there?

potent sleet
#

for next time. For now just look over the tasks I told you alredy

#

I already sent what to do

sour zealot
#

okay

jaunty sleet
#

will I get an error if I try to stop a coroutine that is not running?

#

and if so how do I check if it is running or not?

heady iris
#

maybe if you pass a null to StopCoroutine

#

but i'm pretty sure it's a non-error to stop a coroutine that isn't running, in general

jaunty sleet
#

ok, thanks

buoyant arrow
#

please ping with response

I want to have a sphere that serves as a boundary for a player. The sphere is large and transparent, and the player is within such sphere. Imagine the sphere is hollow.

I want collision to occur only when the player has collided with the inner surface of the sphere (imagine the sphere is hollow). However, I do not want collision within the sphere. How do I go about this?

hexed pecan
#

Sounds like you need a MeshCollider

#

Make a sphere mesh, flip its faces/normals and use that as the meshcollider's mesh

buoyant arrow
#

Will try—thank you!

hexed pecan
#

Another cheap option is to use a distance check from the center of the sphere to the player and do manual checks that way

#

But im not sure if thats suitable for your use case. If you need actual collisions, use what I first suggested

hushed needle
#

Hello, I am watching a tutorial video for Unity and in that video that man wrote a few lines of code and when I wrote the same code I received an error (the video is from 8 years ago) is this because the video is old?

somber nacelle
#

it looks like gridWorldSize is a Vector2 but you are trying to divide a float by gridWorldSize and store the result in a float. are you certain you don't want to be accessing the individual axes of that vector2?

simple egret
#

Basic operators between common types haven't changed in years, so your code is probably different

somber nacelle
#

yours is different

simple egret
#

It's not the same

#

Near the end of the lines

hushed needle
#

i am blind

dusk apex
# hushed needle this code:
var mistake = 2f / new Vector2(10f, 6f);//Error dividing a float by a Vector2 - they cannot operate in this way.```
#
var mistake = 2f / new Vector2(10f, 6f).x;//Legal - dirty example```
quasi lily
#

How do I get third person shooting that doesn't shoot around corners like this

#

I've watched multiple tutorials and they all allow look at where the camera is focused on but it always allows the character to shoot backwards

hexed pecan
#

Whats going on here, are the bullets supposed to fly straight?

knotty sun
dusk apex
quasi lily
#

Well they seem to be colliding with the player but that's a separate issue

#

Ok well I can show the code it's just a lot

dusk apex
#

!code

hexed pecan
hushed needle
#

I can't believe it.

dusk apex
#

Is the bot down? !code

hexed pecan
#

!code please

signal moon
#

hi would anyone spare 5 mins to help me solve one little frustrating and probbably very simple error with my buttons?

hexed pecan
#

People will help if they can

signal moon
#

well, it would be easier if ill show it, bcs its probably not only code issue, and i dont want to spam

dusk apex
hexed pecan
#

Dalphat is the bot now

dusk apex
#

Really didn't want to see the screen flood.

quasi lily
hexed pecan
#

Make a thread if youre concerned about spamminess

quasi lily
#

This is all the code it's just a lot of like inheritance stuff

#

oh wait and I need the code for actually shooting the bullet 1 sec

#

This is the weapon script

#

The collision stuff isn't working as intended but the shooting technically is, it's just the approach seems to be wrong, but every tutorial I watch tells me to do it like that lol

dusk apex
# quasi lily Well they seem to be colliding with the player but that's a separate issue

Without looking too much into the code I would consider checking if the shot direction is in the same direction as the target point. The wall was behind the player but in front of the camera. You can use dot product to determine if they are in the same direction or not - positive would be both facing the same way whereas negative would be the opposite (target was well behind the player!)

signal moon
#

ok, i wanted to show somebody on stream but ok, so i have this piece of code. i done it partly with chat gpt bcs i post things here when chat cannot help. ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Przyciski : MonoBehaviour
{
public ProgressBar xp;
public Abilities ability;
private Button button;

void Start()
{
    // Get the button component
    button = GetComponent<Button>();

    // Set the normal color to 110E0E
    ColorBlock colors = button.colors;
    if (colors == null)
    {
        colors = new ColorBlock();
    }
    colors.normalColor = new Color(0.066f, 0.055f, 0.055f);
    colors.colorMultiplier = 1;
    button.colors = colors;
}

public void OnClickLaser()
{
    if (xp.SkillPoints >= 1)
    {
        ability.laser = true;
        ability.laserPoints++;
        xp.SkillPoints = xp.SkillPoints - 1;

        // Set the button's colors to white
        ColorBlock colors = button.colors;
        colors.normalColor = Color.white;
        colors.highlightedColor = Color.white;
        button.colors = colors;
    }
}``` later parts are basically the same thing but for different buttons. i want the buttons to be almost black, then when highlited to be white, and when clicked and function is played to stay white forever. my error message is NullReferenceException: Object reference not set to an instance of an object

Przyciski.Start () (at Assets/Skrypty/Przyciski.cs:18)
(its a full one)

dusk apex
#

You've got a null reference exception error on line 18

#

What line is 18?

signal moon
#

ColorBlock colors = button.colors;

dusk apex
#

So button was null.

simple egret
#

And indeed, there's no Button aside this script in the Inspector, so the GetComponent<Button>() earlier fails

dusk apex
#

Quick tip: GetComponent can return null.

signal moon
#

and how do i fix it? im a beginner, thats why i even asked this question

simple egret
#

Also note that we don't help with code that's generated by AI

dusk apex
#

It would return null when you've not got a button on the same object.

signal moon
#

the script is attached to both button and canvas

wide terrace
#

The canvas does not have a button component

dusk apex
#

For best practices, have the reference variable as public or [SerializeField] private and drag/drop the object into the Editor's inspector field.
You'd remove the GetComponent call if doing so in this way.

simple egret
#

Yeah having that script on the Canvas itself isn't logical

signal moon
#

ok, i thought that it will aply to children and then i changed the code again so its on every single one of them

#

so its useless by now

simple egret
#

The code explitly says "get a Button on this object", so placing it on an object that has no Button may result in the error you're getting

signal moon
#

ok thx its solved

#

but since im here, ill ask for help with my last error, that is also the same topic, and same error, but with different things

#

so

#
ProgressBar.Update () (at Assets/Skrypty/ProgressBar.cs:34)``` my code is ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ProgressBar : MonoBehaviour
{
    public HeroKnight heroknight;
    public Image ProgressBarImage;
    public int AllEnemies;
    public int DeadEnemies;
    public int PlayerLevel = 1;
    public int SkillPoints = 0;

    private void Start()
    {
        // Count the number of enemies in the scene
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
        AllEnemies = enemies.Length;

        // Call UpdateProgressBar to set the initial progress bar value
        UpdateProgressBar();
    }

    private void Update()
    {
        // Call UpdateProgressBar every frame to update the progress bar value
        UpdateProgressBar();
        if(AllEnemies==DeadEnemies)
        {
            DeadEnemies = 0;
            SkillPoints++;
            PlayerLevel++;
            heroknight.currentHealth = heroknight.maxHealth;
        }
    }

    private void UpdateProgressBar()
    {
        // Calculate the fill amount based on the number of dead enemies and the total number of enemies
        float fillAmount = (float)DeadEnemies / AllEnemies;

        // Set the fill amount of the progress bar image
        ProgressBarImage.fillAmount = fillAmount;
    }
}```  the error occurs when i kill all enemies, so when if(allenemies....) is triggered
#

it wasnt there before i done my buttons

dusk apex
#

at Assets/Skrypty/ProgressBar.cs:34
The number 34 above indicates that it occurred on line 34.

signal moon
#

but line 34 is heroknight.currentHealth = heroknight.maxHealth;

dusk apex
#

Wherever that may be

#

So an NRE occurs when you try to access a member of something null.

#

heroknight was null (which is fine) but because you tried accessing currentHealth and or maxHealth, the error occurred.

quasi lily
#

ok sweet fixed that issue thx ppl

dusk apex
#

Luckily they were both the same reference so you did not have to play guessing games. heroknight was null. Figure out why.

signal moon
#

might it be the issue with progresbar not being attached to heroknight?

wide terrace
#

Your code doesn't seem to assume it would be attached to a heroknight. I would guess that you haven't dragged an object into the Heroknight field in the inspector

winged tiger
#
obj.Translate(obj.forward * moveSpeed * Time.deltaTime);

why in the world this moves the obj on the global x axis

wide terrace
#

presumably because obj's z axis is aligned with the global x axis?

winged tiger
#

no

#

it's rotating

simple egret
#

Nah it's because .Translate is alrealy local space

wide terrace
#

ahhh

winged tiger
#

oh and that

simple egret
#

You need to do Vector3.forward * ...

signal moon
winged tiger
#

Vector3.forward * obj.rotation?

simple egret
#
  • deltaTime, but yes
signal moon
#

idk if thats good or bad, couse my problem isnt occured by errors

#

but atleast now i know whats going on

#

Thank you!

winged tiger
simple egret
#

Post the new line of code, as well as obj in the scene with the move tool arrows visible, and in Pivot + Local mode

winged tiger
#
obj.Rotate(obj.up,rotateKosiarka);
obj.Translate(obj.rotation * Vector3.forward * moveSpeed * Time.deltaTime);```
winged tiger
simple egret
#

Still not good, why did you multiply with rotation?

#

This makes the resulting vector local again

remote abyss
#

If anyone can help me pls, not sure what is going on. I have a particle effect as a PreFab. If I put it on a missile with a force and when I place the missle in the scene by itself it will fly into another object and explode and the particle effect plays correctly. But I instantiate it from the spaceship, the firepoint is placed WAY of the spaceship object just to test even and as soon as I fire the missile it explodes underneath he ship itself no matter how far out I put the firepoint?

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

public class MissileController : MonoBehaviour
{
    public float missileSpeed = 30f;
    public Rigidbody rb;
    public GameObject hitParticlePrefab;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        rb.AddForce(transform.up * missileSpeed);
    }

    private void OnCollisionEnter(Collision collision)
    {
            Instantiate(hitParticlePrefab, transform.position, Quaternion.identity);
            Destroy(gameObject);             
    }
}```
Here is the code on the missile to trigger on impact. What am I missing pls?
winged tiger
#

ohh

#

wait

#

.Translate is local

#

ah man

remote abyss
#

bah code block didnt work 😦

winged tiger
#

3 times `

simple egret
#

Backticks ```, not quotes

remote abyss
#

yeah noticed lol sorry

simple egret
quaint crypt
#

how do I convert from whatever Object type LoadAssetAtOath returns to my generic T type?
T prefab = AssetDatabase.LoadAssetAtPath<T>(path);
It gives an error saying there is no type conversion from UnityEngine.Object to T, and no boxing conversion.

simple egret
#

Constrain your type to what it needs, at the class declaration: class C<T> where T : Object { }

remote abyss
#

@simple egret Correct. script is only on missile

simple egret
#

Okay, can you Debug.Log the position of the missile when it collides with something? And verify that the position is the one you're expecting (ie. the hit point, not your spaceship pos)

remote abyss
#

@simple egret Bah good suggestion, thx man. I do that all the time just dont know why I didnt think of doing that now lol.

#

Im like the Debug god normally lol

remote abyss
#

@simple egret Thx man fixed it. Got some wierd unknown to man reason I had added a
missile.transform.position = transform.position;. LOL

heady iris
#

the missile knows where it is...

remote abyss
#

Hehe yeah

shrewd meteor
potent sleet
dim gale
#

Can anyone help me with a coding problem?

dim gale
#

sorry

#

this is the basic idea of my app

#

when you press add a input field comes up asking you to type in how much money you want to add

#

same for subract

woeful slate
#

If I have a WebSocketClient that I'd like all my characters to be able to access, what's the best way to do that? A singleton with the instance?

dim gale
#

when you subract once it works but subtracting multiple times doesnt add it to the last one just resets it

#

and the code for adding is the same like for subtracting but it doesnt work

dim gale
#

sorry if i sound stupid

#

DODAJ means add and ODUZMI means subract in my language

potent sleet
#

ugh dyno

#

!code

dim gale
#

!code

potent sleet
#

how to post code

#

idk why bots asleep

dim gale
#

yeah doesnt work

#

can you still see the code?

potent sleet
#

no use a site I can't read lines

dim gale
#

what site

#

oh

#

wait

potent sleet
#

it's in the readme

regal epoch
#

when I run my game on my phone, lock the screen, and turn my phone on again, the game is viewed on top of the lockscreen. Anyone know how to get rid of this "feature"?

dim gale
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using TMPro;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour
{
    public Text money;
    public InputField DODAJ;
    public InputField ODUZMI;
    public float moneyNumberAdd;
    public float moneyNumberSubract;
    private float moneyAll;
    public GameObject moneyText;
    float result1;
    float result2;

    void Start()

    {
        Camera.main.clearFlags = CameraClearFlags.SolidColor;
        Camera.main.backgroundColor = Color.yellow;

    }
    public void onClickDodaj() 
    {
        DODAJ.gameObject.SetActive(true);
        ODUZMI.gameObject.SetActive(false);
        ODUZMI.text = "";
    }
    public void onClickOduzmi()
    {
        ODUZMI.gameObject.SetActive(true);
        DODAJ.gameObject.SetActive(false);
        DODAJ.text = "";
    }
    void Update()
    {
        if(moneyAll < 0)
        {
            Camera.main.clearFlags = CameraClearFlags.SolidColor;
            Camera.main.backgroundColor = Color.red;
        }
        float.TryParse(DODAJ.text, out float result1);
        moneyNumberAdd = result1;
        Debug.Log(moneyNumberAdd);

        float.TryParse(ODUZMI.text, out float result2);
        moneyNumberSubract = result2;
        Debug.Log(moneyNumberSubract);
        if (Input.GetKeyDown(KeyCode.Return))
        {
            //code for adding 
            Debug.Log(DODAJ.GetComponent<InputField>().text);
            DODAJ.gameObject.SetActive(false);
            DODAJ.text = "";
            moneyAll = + moneyNumberAdd;
            moneyText.GetComponent<Text>().text = " " + moneyAll;

            //code for adding
            Debug.Log(ODUZMI.GetComponent<InputField>().text);
            ODUZMI.gameObject.SetActive(false);
            ODUZMI.text = "";
            moneyAll = - moneyNumberSubract;
            moneyText.GetComponent<Text>().text = " " + moneyAll;
        }
    }
}
regal epoch
#

It's a unity question that could maybe be solved by code

potent sleet
regal epoch
#

idk

regal epoch
#

why not

potent sleet
dim gale
#

never heard of regex

potent sleet
#

you can just make the field "numbers only"

#

so you dont have to do this
float.TryParse(ODUZMI.text, out float result2);

dim gale
#

yeah i did that

#

oh

#

idk how other i would do it

simple egret
#

Also if you're using TryParse, actually use the bool it returns to clear the input if it couldn't be converted to a number!

#

Or show a message to the user, whatever

dim gale
#

okay but why does the subtract code work fine but the add code not

potent sleet
#

or decimals if you use decimals

dim gale
#

yeah i made it decimal already

#

but i dont know how i would save it in code

#

without using tryParse

simple egret
#

You need that, or Parse since you're sure it's a number already

dim gale
#

parse didnt work

simple egret
#

The issue lies in the part where you add or subtract

potent sleet
#

oh true

#

thought InputField has a method or something

dim gale
#

sorry im new to coding

potent sleet
simple egret
#

You do a = + b instead of a = a + b

#

Or, a += b which is a shortcut

potent sleet
#

^

dim gale
#

ohhhhh damnnnn

#

i feel so fricking dumb

#

works perfectly fine now

#

thank you @potent sleet and @simple egret

#

appreciate it❤️

potent sleet
#

this is strange though
DODAJ.GetComponent<InputField>().text

DODAJ is already InputField

#

just do DODAJ.text

dim gale
#

oh

#

yeah didnt see that

#

well thank you

simple egret
#

And for the parsing, you can do float n = float.Parse(DODAJ.text). It raises an error if what you pass isn't a valid number, but as the input field constrains your input to a valid number, it won't ever raise the error

#

TryParse is more for the cases where you don't have a constrained input, or you don't trust the user

shrewd meteor
potent sleet
#

and saved

#

you saw edit too ?
You should only have
PlaceOnNavMesh();
running in start

shrewd meteor
# potent sleet You commented out all those things ?

yeah, I've realised the true problem, for some reason, the line "_Agent = GetComponent<NavMeshAgent>();" puts the capsule in the floor. I have no idea why seeing as the gameobject it's attached to is not (4.50, 0.08, 0.00) and i dunno where it's getting these coordinates from

potent sleet
shrewd meteor
#

literally the moment I activate the NavMeshAgent, it get's "0.08" on the y axis from somewhere

shrewd meteor
shrewd meteor
potent sleet
barren void
#

is there a way to convert this event to hold event?

        _decrementButton.onClick.AddListener(OnDecrement);
        _incrementButton.onClick.AddListener(OnIncrement);```
Cause it's time consuming when the decrement/increment action only triggers per click. Is there a onPressed function?
potent sleet
#

also try just
[SerializeField] private NavMeshAgent _Agent;
and setting it in the inspector

shrewd meteor
potent sleet
shrewd meteor
potent sleet
potent sleet
barren void
#

is this own button, a new class inherited to Button?

potent sleet
#

you make a script and put those two interfaces with their respective implementation

#

then use image component instead of Button

barren void
#

ohhh I get it, so its like overriding the default button script

potent sleet
# barren void ohhh I get it, so its like overriding the default button script
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
 
public class MyButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
 
public bool buttonHeld;
 
public void OnPointerDown(PointerEventData eventData){
     buttonHeld = true;
}
 
public void OnPointerUp(PointerEventData eventData){
    buttonHeld = false;
}
}```
#

you can reference the Image component if you wanna change the sprite

#

or color

barren void
#

but the pressed/unpressed anim like state will be removed right? the base and pressed color what I meant

shrewd meteor
potent sleet
barren void
#

okay thank you, overhaul it is

shrewd meteor
potent sleet
#

try debugging visually hit.position
I have no idea where 0.08 is

shrewd meteor
potent sleet
#

bruh

#

you have 2

#

on which doesn't belong

#

the proper usage is the if statement one

#

also like i said 0.08 sounds like the navmesh height from the ground if ground is at 0,0,0

shrewd meteor
#

I'm starting to think this is going back to changing the pivot point

potent sleet
#

which it isn't since it's returning the sampled position

#

or maybe it didn't

#

you should debug it since it's an If statement

#
if(NavMesh.SamplePosition(etc..
...etc
else

Debug.Log("No valid Position on Navmesh found")```
shrewd meteor
#

I'm so damn confused

potent sleet
#

in the sampleposition

#

if warp is running though it does find a valid position

shrewd meteor
potent sleet
#

just try this

shrewd meteor
potent sleet
#

try deleting this agent and make a new one

#

test same script with new agent

shrewd meteor
#

aight bet

potent sleet
#

make sure you baked the correct navmesh too

#

correct layers and all

shrewd meteor
shrewd meteor
potent sleet
potent sleet
potent sleet
warped lagoon
#

Hey folks, anyone have any idea why I cannot see Physics Shape/Body on my project? Pretty much have all thje same packages as the DOTS Sample project but cannot get it to show up...

#

com.unity.physics@1.0.0-pre65

tardy mortar
#

I have a scriptable object that serializes abstract classes. Though, every time I want to add a new class to the list, I have to recreate the scriptable object. Is there a workaround for this?

public class D_Abilities : ScriptableObject
{
    [SerializeReference]
    public List<Ability> abilities = new List<Ability>
    {
        new MagicSeedAbility(), // abstract class
        new SummonPlagueAbility()
    };

    public GameObject abilityPrefab;
}
leaden ice
#

Otherwise there's no way to choose what kind of ability to add in the UI

golden vessel
#

Hey, I have an array of Spell, which is a struct. I want to either assign it or not depending on the player having a spell equipped at that slot.
How do I check if it's assigned or not?
I tried spells[i] == default(Spell), however the compiler says that I can't compare Spell and Spell (?)
Also heard of nullable value types, not sure how I accomplish that

rotund bison
#

There are a few libraries that exist to deal with the editor if you just wanna get it over with

#

I think one of them was called SerializeReferenceExtensions or sumtn

#

think Odin also has something that does it

leaden ice
golden vessel
golden vessel
somber nacelle
golden vessel
#

Spell[] spells = new Spell[5];
if (spells[i] == default(Spell))
I'm pretty sure they are the same type

golden vessel
leaden ice
#

You have to define the == operator for it

leaden ice
#

Equality checking works differently for value types than it does for reference types

golden vessel
#

Ok, good to know

leaden ice
#

There's a default comparison for reference types that uses the object address

#

Structs don't use reference variables so that can't be done in C#

golden vessel
#

Well I learnt something

#

Thanks ❤️

lusty dragon
#

Guys have you got any idea as of why the clamping does not work and it just keeps my vertical movment at 0?
instead of 0 to -90

  private void FixedUpdate()
  {
    float angleY = 0;
    float angleX = 0;

    if (turning)
    {
      // Calculate the rotation angle and direction
      angleY = turnSpeed * Time.fixedDeltaTime * (turnRight ? 1f : -1f);
    }

    if (_tilting)
    {
      // Calculate the rotation angle and direction
      angleX = tiltSpeed * Time.fixedDeltaTime * (_tiltUp ? 1f : -1f);
    }

    // Apply the rotation on global axes
    transform.eulerAngles += new Vector3(angleX, angleY, 0);

    // Clamp the x-axis rotation between -90 and 0 degrees
    Vector3 currentRotation = transform.eulerAngles;
    currentRotation.x = Mathf.Clamp(currentRotation.x, -90f, 0f);
    transform.eulerAngles = currentRotation;
  }```
somber nacelle
#

eulerAngles are interpreted from the quaternion at the time you access them. this means they can be either signed or unsigned depending on how they feel at the time you access it. This also makes clamping an axis on the eulerAngles property after rotating it harder than just manually tracking your rotation as a float and clamping that before assigning it to the rotation

#

search "clamp rotation" in this discord and you'll see plenty of examples of how you could do so

humble temple
#

anyone know why a meshrenderer with its materials array, having two elements in it, will create instanced versions of those materials during runtime? this seems to be what is preventing me from chaning the materials during runtime with a script

quaint rock
#

how are you trying to change it via script

#

its the accessing via render.material that is making them instanced

humble temple
#

in my script i have Material mat1, mat2, mat3 and so on. the materials are dragged into the inspector.
the script looks like this

tabletMesh = GetComponent<MeshRenderer>();


tabletMesh.materials[1] = mat4;
humble temple
#

my code above was my first attempt.

humble temple
rain minnow
# humble temple

accessing materials instantiates the materials and makes them unique to this renderer. that's why they are instanced, bc they only affect this object . . .

humble temple
#

ok, that makes sense. so what is the right way to change the materail during runtime?

#

you think it should work? darn. its not.

#

actually i think it is.

rain minnow
ashen yoke
#

you mean swap? you can swap material just swap sharedMaterials

#

material is a getter for the currently used material, if it was unchanged it will return the original shared material, which is the asset

#

if you assign anything to it it will either assign the new or create a copy

#

to protect the asset from changes

#

if you didnt assign anything and didnt change you can just swap shared material for another asset reference

quasi lily
#

Why am I getting Cannot resolve symbol 'Invoke' and Cannot resolve symbol 'Instantiate'

#

Like they just don't exist in the context of this interface

#

But the entire enemy script is based around interfaces so like what am I supposed to do to instantiate the enemy projectiles

leaden ice
#

If you're writing an interface, they don't exist unless you defined them

quasi lily
#

So like

#

Is there any way I can implement this in my interface?

leaden ice
#

Sure, add those to your interface

quasi lily
#

Like code Instantiate and Invoke myself??

leaden ice
#

No

#

Just add them to the interface

#

Interfaces don't contain implementation

#

Just the signature

leaden ice
#

So there's no need to do anything with Instantiate

quasi lily
#

wait it's not even an interface

#

its a class that implements an interface

#

I could just also get it to inherit from Monobehaviour then right?

leaden ice
#

Did you forget to derive from Monobehaviour?

leaden ice
#

And what that means for your class

quasi lily
#

I do not really but no red line makes brain happy 🙂

#

If it breaks later then like

#

idk what isn't breaking atm

leaden ice
#

It's one of the most basic things in Unity scripting

#

Monobehaviours define components you can attach to GameObjects

quasi lily
#

I mean I just know it as script thing with all the main unity commands

leaden ice
#

Do you know what a component is

quasi lily
#

yeah like something you attach to an object

leaden ice
#

Yes

#

When you make a Monobehaviour class you're making one of those

#

If it's not a MonoBehaviour it can't be attached to GameObjects

#

You have to manage it yourself in code entirely

quasi lily
#

yh I get that

#

it doesn't seem like it will mess up the system so yeah it should be fine

leaden ice
#

Presumably you know if this class is going to be attached to a GameObject or not

quasi lily
#

it wont

#

but like

#

that shouldn't matter

leaden ice
#

If it won't be then it cannot be a Monobehaviour

#

It matters a lot

#

Invoke will definitely not work on it for example

quasi lily
#

ah

#

dope

#

uh

leaden ice
#

Why do you want invoke anyway

quasi lily
#

yeah ill be real I'm finished bro it

#

like I just was given a script with a statemachine class

#

each state is implemented as an interface

#

and it switches between which state is being executed

leaden ice
#

Sounds like you're in over your head a little

quasi lily
#

No shit lol

#

But it was like the code we were given and it works until I have to extend it to make the enemy shoot instead of just patrol

#

because shooting requires invoking a firing script on a delay and instantiating a bullet prefab, something the current implementation doesn't seem to allow for

#

maybe I just put the shooting code in the actual object that holds the state machine

sterile island
#

I need some help determining which tile the mouse is over when hovering. This is the code I have so far that seems to be the general goto. But I am having issues with the worldPos result being wonky and not mapping to a proper cell.

var mousePos = UnityEngine.Input.mousePosition;
mousePos.z = 1f;
var worldPos = Camera.main.ScreenToWorldPoint(mousePos);
var mapCell = _terrainTileMap.WorldToCell(worldPos);
var tile = _terrainTileMap.GetTile(mapCell);
if (tile == null) return;

The Grid position is 0,0,0 along with the tilemap within it being 0,0,0. The Camera will zoom in and out as part of the controller. I have been stumped on this for hours and every search result comes up with this same solution. But no matter what, the mapCell is always the same. Im not sure what I could be missing here.

quaint rock
#

what mode is the camera in, perspective or ortho

sterile island
#

It is Perspective

quaint rock
#

ScreenToWorldPoint will not do what you think then

#

it gets a point on the near plane of the camera

#

then you can use the resulting ray, to get a position in the world, by raycasting

thorny sparrow
#

Hello. If I have multiple of the same script on one object, how can I reference one of them specifically?

quartz folio
#

Drag a reference to it into a serialized field

sterile island
#

Ah I see with the camera part. I changed it to ortho since I really didnt need it perspective. Now things are changing so I will try working from that. Thanks @quaint rock

thorny sparrow
somber nacelle
#

are you using the correct variable type?

quartz folio
#

Then show what you are trying to drag, and to where. Nobody can help without full context.

thorny sparrow
quartz folio
#

It's unclear where these two objects are, are they both in the same scene?

thorny sparrow
#

one is a prefab

hidden compass
#

Hello, i think i need an extra pair of eyes.. Here in the video, is an enemy ai, the smaller orange circle is the radius of this next script..
i run a foreach with an overlapsphere and check the players velocity to see if he's moving.. if he is -> we update his position.. if not do nothing.
then cs private void Update() { ForgetSounds(); } runs continuously.. to forget everything after so many Ticks

#

he shouldn't be updating the player's position unless he's still inside that orange circle.. but here u can see the orange line draws my position until he forgets the sounds.. which is fine, but it should forget the last position he heard the player within that sphere , had the player exited it..
https://www.spawncampgames.com/paste/?serve=code_508

#

heres the code... something going on in that foreach or something that i dont understand

#

oh, you can see how the vision one stops and turns magenta when the player exits.. yet the hearing one doesn't 🤔

#
    private void OnDrawGizmos()
    {
            Gizmos.color = drawColor;
            if(DetectedPlayer && Player) // && player
                Gizmos.DrawLine(sensePos.position,Player.transform.position);
            else if(Player && !DetectedPlayer)
                Gizmos.DrawLine(sensePos.position,playersLastKnownPosition);
    }``` these are the gizmos
#

adding in player= null; and DetectedPlayer = false at the beginning of the Tick() fixed it for for not detecting once outside the radius but.. then it breaks the ForgetSounds() function..

#

imma have to think about this one..

fresh widget
#

Help required for my AR Game. Look at this code for reference.
https://pastebin.com/iwvJsk0a
This script is attached to an empty GameObject. The function CreatePlayField is assigned to a button's OnClick event. Now the button works, I have tested it with Debug.Log . But it does not generate the plane I want it to in this function. There is a debug.log in Update function I used to know how this function works. That debug statement tells vector difference between positions of a Quad and generated plane. The debug text is empty which alludes that the plane is not generated. The quad is there. The plane is not. Can someone tell what I might be doing wrong here ?

Some screenshots are attached for better understanding

simple sable
#

Hey everyone.

So I have this script that chooses a random position in my world and I want to check if that point is inside of a collider. I searched on the internet on how to do it and I ended up with this line of code.
Then, I check if "collider" is null or not and that should tell me if the point is inside a collider or not. But for some reason, it doesn't work, and I'm not sure why.

ashen yoke
#

what doesnt work

#

the null check? the overlap?

#

are you sure the collider is on layer 6?

simple edge
#

Fairly sure layermask needs to be bitshifted
Try 1 << LayerMask.LayerToName(6)

somber nacelle
simple edge
#

Ah fair enough

#

Yeah I was thinking of NameToLayer

simple sable
#

Yep, my Tilemap Collider 2D is on that 6th layer.

The null check always returns false, even though I can see in the scene view that the point is inside of a collider by just spawning an object at that position.

simple sable
#

I'm not sure what that means.

simple edge
#

Shift it to the left 6 times

somber nacelle
#

i mean a better option than manually bit shifting is just to create a LayerMask variable that you set in the inspector

ashen yoke
#

yes

somber nacelle
#

also it sounds like you might have a specific collider you are checking against, if that is the case why not use Collider2D.OverlapPoint instead?

cosmic rain
ashen yoke
#

0010 0000

#

cat_at_the_table_girl_screaming.jpg

cosmic rain
#

Does that mean that 1<<1 is 0000 0001?🤔

somber nacelle
#

i'm gonna have to agree with dlich on this, 1 << 6 is 64

simple sable
somber nacelle
#

ah, fair enough

simple sable
ashen yoke
#

1 << 0 is 0001

ashen yoke
#

UnityEditor.TransformUtils.SetInspectorRotation()

visual fractal
#

My movement script is messed up. When I try to walk or sprint, I don't move, but if I let go of sprint, I get kind of catapulted forwards and stop slowly. Can someone help?

cursive moth
simple sable
#

That was the problem.

cerulean bloom
#

hey guys im trying to make a game where the theme is you cant do the same thing twice like walking and i made the controls WASD teleport you a square infront but now i have a issue where i can go straight thru colliders and my script just isnt working to account for that,can someone help https://hatebin.com/crsnjyddze

ruby fulcrum
#

is it alright to have functions with non capitalized letter at the start

#

i just saw the naming convention warning but all my functions are already non capitalized

winged mortar
ruby fulcrum
#

but would it affect the performance

winged mortar
#

And pretty much everyone uses PascalCase

#

No

#

Not at all

ruby fulcrum
#

ah alr then

winged mortar
#

Functionally not different

#

Make sure you are consistent with your naming though

#

It reduces visual load when trying to read your code back

ruby fulcrum
#

i name my coroutines with capitalized at the start

winged mortar
#

It instantly becomes clear that you are looking at a function

ruby fulcrum
#

and functions with non capitalized

winged mortar
#

Now that's confusing

ruby fulcrum
#

think that helps to differentiate

#

i mean it works for me

#

i saw the warning for coroutine and assumed all coroutines needed pascal

#

didnt know it applied to functions too

winged mortar
#

If it works for you then it's fine

#

Might be worth checking it out

thin aurora
#

You can disable the warning, if you would like to stick to it

#

There's really no "best" way with this. There's just the way that the majority of people considered best practice, and nobody forces you to stick with it

soft igloo
#

hey I am trying to build a dynamic traffic signal system I am new to unity and I just want to make a simulation does anyone have any base project I can start working on to build the dynamic traffic signal system

shrewd meteor
dim crypt
#

Anyone know how i might get a sheetmetal effect in unity? and what i mean by that is having the object bending and deforming, but not too bendy.

Want to have it that you can push a mesh like this against a wall and it bends and conforms as it is pushed against the wall.

halcyon radish
#

Hey, morning guys, i've been getting a "A Native Collection has not been disposed..." error regarding memory leak when doing a web request. This has only started showing when I upgraded to 2021.3.6f1, which was a few months ago.

Before we where using 2020.### (don't remember the exact version), but as we upgraded my computer at the start of the year we decided to upgrade the version of unity we where using. Because we had a few other features to work through, I didn't think to address this issue until now. I do have the web request wrapped in a using statement and also call dispose at the end of the call. Even while I do so the error still appears.

It may be obvious to someone else what I might be missing, i'll attach screenshots of the error and the code snippet. If you need any other clarification just let me know.

thin aurora
#

Also, side note, suggest you look into Newtonsoft when it comes to serializing data to JSON

#

JSONUtility is very bad

halcyon radish
#

Nope, i'm not at all.

swift aspen
#

should you really be disposing your webRequest when using implicitly disposes it?

halcyon radish
halcyon radish
#

In the stack trace it was pointing to my request script, which is why I thought i would need to dispose somewhere along the line.

swift aspen
halcyon radish
thin aurora
#

It's one of the many things JSonUtility can't do

#

You would need to wrap it around an object, lol

#

There's a whole lot of things it can't do, hence why I strongly suggest you ditch it asap

halcyon radish
swift aspen
#

Which screenshot? You added the upload not the download

#

also the UploadHandlerRaw also needs the dispose from the looks of it

halcyon radish
#

I was referring to my initial post.

swift aspen
#

So try removing your manual .Dispose() while keeping both dispose...OnDispose = true

swift aspen
#

Yeah exactly you only did for Upload, you need to do it for Download as well

halcyon radish
#

Ohhhhhh, my mistake. Got you.

#

Let me try that.

swift aspen
#

Both of those types, UploadHandlerRaw and DownloadHandlerBuffer mention that they allocate Native Memory. Whenever something allocates native memory you need to dispose it somehow. In your case the UnityWebRequest seem to be able to do it for your through the dispose...OnDispose functions

halcyon radish
soft igloo
cosmic rain
swift falcon
burnt echo
#

Hey, so I'm trying to do some decoupling, I feel like my stuff is getting really spaghetti'd and I'd like to do a clean up before I continue and make the project bigger.

I have 5 singleton systems/managers, including a GameManager, and they're all just referenced where I've needed them.

Could someone point me to some resources to clean up all my references? Maybe give me the name of a better design method I could research?

cosmic rain
burnt echo
#

Actually make it 4, I forgot one is just the scene controller, I don't think I need to count that. Lol

I'm doing a kind of idle/resource management game that's all UI based so each of the current singletons are set up for tracking and handling different "resources".

RosterManager handles the minion counts, as well as assigning them to different jobs (sub-rosters).

I have an Income manager that handles everything with the currency; gaining, spending, tracking

Suspicion manager, etc

Stuff like that. I think I've done a pretty good job keeping them all in their own lane, and since everything is UI based, I think most of the game needs to know about what they're doing, I"m just trying to find a cleaner way of getting the data from each of them

dusk apex
#

You've got a lot of managers. Unless it's multiplayer and you're evaluating the statistics of multiple players, the data could be stored locally on the Players.

swift falcon
#

do all those objects have a single script and need to be inside the same scenes? if so you CAN just slap all the scripts on one manager object at the very least

burnt echo
#

They are all currently on their own scene objects and are single scripts

dusk apex
#

Dependency on third party objects is a boiler plate that I'd avoid unless necessary - ease of access has legitimate uses in game dev but often times is abused.

burnt echo
#

Yea, I mean I still consider myself to be new at game dev. This is my biggest project so far at like 1200 lines, so it's nothing ridiculous, but I want to learn to do it "correctly" and I can already feel that things are getting kind of messy and tangled, so I'm just looking for options, patterns, etc

#

Everything is working great though, I have no other issues besides a dirty feeling. Lmao

quaint rock
#

just work on a paticular problem at a time

dusk apex
#

Don't want to ruin your fun. Finish it and remake it a dozen times later.

quaint rock
#

games really do not have a overall approach to follow since things differ much more then in other domains of software

#

and unity makes traditional dependency managment harder

#

due to not having just 1 entry point and being able to easily pass stuff down via constructors

dusk apex
#

We're just mangling a bunch of callbacks and whatnot together..

burnt echo
#

Alright, that does make me feel better, thanks a lot guys

quaint rock
#

like everything i do at work is really a big pile of different approaches for different problems

burnt echo
#

Yea, I'm a dev for a medical software company, but I'm trying to get more into games and it is a very different beast. Lol

quaint rock
#

also what i do recommend is do not abstract too early

quaint rock
light beacon
#

hi all, I have this weird thing going on with the tilemap as my player chracter collides with another 2d object. Any idea what it is?

dusk apex
light beacon
#

its like the tile lines are flashing while im colliding with an object

mental rover
dusk apex
#

Moving in tiny increments can produce this artifact. There are some work arounds.

light beacon
#

damn

#

works like a charm the perfect pixel issue. ty all who helped

halcyon radish
thin aurora
#

You would need to wrap it into an object

halcyon radish
thin aurora
#

Helping Unity users to a better future, one user a day.

hollow hound
#

How to disable field sorting in Rider?
I've already removed all "sortBy" inside "fields" in file layout, but it still rearranges fields.

potent sleet
plush sparrow
#

In net code is there a way to check if the user is host or a client?

shrewd meteor
primal wind
#

Happens to the best of us

static lantern
#

Run into this issue a couple of times now. Anyone know why, when I serialize data using JsonUtility.ToJson(), it just returns a pair of brackets?

primal wind
#

Because it probably doesn't know what to do

#

What are you trying to serialize?

#

JsonUtility is pretty limited

static lantern
#
public struct WorldData
{
    public string name { get; private set; }
    public Dictionary<string, CharacterData> Characters { get; set; }
[Serializable]
public struct CharacterData
{
    public string id { get; private set; }
    public string name { get; private set; }
    public int credits { get; private set; }

    public CharacterData(string id, string name, int credits)
    {
        this.id = id;
        this.name = name;
        this.credits = credits;
    }
}
primal wind
#

It can't handle Dictionaries

static lantern
#

Alright, standby

#

Commented that out, same results

primal wind
#

It has other limitations

hexed pecan
#

Probably cant serialize a property either

primal wind
#

Let me find them

hexed pecan
static lantern
static lantern
primal wind
#

Uh

late lion
#

JsonUtility has the same limitations as any serialization in Unity, it's all the same serializer behind it. That means no properties, unless you have a [field: SerializeField] attribute on it, and fields must be public or have [SerializeField]

primal wind
#

Honestly i would just use Newtonsoft.Json but that's your choice

static lantern
#

I really should.

potent sleet
static lantern
#

Unity really be like "dictionaries who?"

primal wind
#

Yeah it's kinda annoying

shrewd meteor
static lantern
#

Kind of makes you wonder why Unity even bothered making JsonUtility when they could have just baked in the open source NSJS

heady iris
#

they did use it internally until recently

#

now it's just an easy-to-install package

#

notice how it used to say it's "not supported"

primal wind
#

So i wasn't dreaming, it was in the manager at some point

twin nacelle
#

any channel to ask for help or here?

heady iris
#

i presume JsonUtility was slapped together a long time ago

late lion
#

When CoreCLR arrives, we can use System.Text.Json 🙏

primal wind
#

CoreCLR?

late lion
#

The latest .NET runtime where are the new C# features are being added. Unity is stuck with Mono/.NET Standard 2.1 until they migrate to CoreCLR, which is underway.

primal wind
#

Oh cool

primal wind
#

Then maybe I'll get to use System.Random.Shuffle before i become 50

heady iris
heady iris
#

neat

#

i've written the fisher-yates shuffle a few timse now lol

primal wind
static lantern
heady iris
#

it goes in an extension method :p

#

but yes, I think i'll just be using the shuffle method now

static lantern
#

Watch the shuffle be the same algo

heady iris
#

it probably is

#

the only drawback is that this isn't using UnityEngine.Random

#

which cooooould be relevant for seeded stuff

#

but, not really: you'd already have a separate RNG for the shuffling

#

it's a wash

static lantern
#

Well this is an odd example to use. From Wikipedia:

heady iris
#

🤯

#

meanwhile on the Bayes' Theorem page

primal wind
#

Oh god

#

And i though getting Rick rolled by the official Svelte course was bad

static lantern
#

...why you gotta bring up webdev?

#

I drink because of webdev

primal wind
#

It reminded me of it

heady iris
#

i haven't touched that in a while. i am recovering.

static lantern
#

cries in php

primal wind
#

It's not my job so i guess it helps not becoming crazy

dusky lake
#

cries in ts

static lantern
primal wind
#

I wanted to make a website for my stuff and a friend recommended Svelte which seemed so much easier and friendly that every other popular option

#

React still gives me nightmares

heady iris
#

i can at least understand what my old ts code does

dusky lake
#

Oh react is easy... its just like html, right... right? cry_thumbsup

heady iris
#

static type checking is such a godsend

#

it's why C# doesn't make me sad (too much)

static lantern
#

Would be nice if browsers natively supported TS but, eh.. what can you do?

dusky lake
primal wind
#

If i could make everything with C# i would

heady iris
primal wind
#

No one would stop me

heady iris
#

i struggle to do anything with them

heady iris
static lantern
#

/s

thin aurora
#

It's just very shitty to set up

#

Something about setting up the linker for it to work properly

#

So totally not worth it

heady iris
#

don't be a coward. just serialize data via memcpy.

thin aurora
#

Just ToString() your class and store that instead

#

Why so complicated

static lantern
heady iris
#

cat /dev/mem > save

#

wait, isn't that basically a save-state

static lantern
thin aurora
static lantern
heady iris
static lantern
#

Huh

#

TIL

heady iris
#

but anyway, unity,

static lantern
#

yes, unity

#

quality product

#

no problems

#

10/10

heady iris
#

it hasn't randomly frozen on me in a while on my macbook

primal wind
#

Unity is great but the issues can't be ignored eternally

heady iris
#

they also fixed the random SRP crash

#

very nice

static lantern
primal wind
#

Uh

#

I legit never got a crash that wasn't my fault so i guess I'm lucky

#

I'm really interested in how Minecraft shaders work cause i would really like to make something like them in Unity. They should be lighter than regular realtime lights

#

I'll have to poke around one

static lantern
primal wind
#

Even if I'm a beginner at shaders

#

Oh

static lantern
#

He ELI5, but made it clear it can get very deep and encouraged me to learn Algebra from scratch

heady iris
#

shaders are cool

primal wind
#

I'm not that great at maths

static lantern
#

Since, when I was in high school, I ignored algebra like my mother ignored my father's alchoholism

heady iris
#

i need to learn more about writing shaders that are more physically realistic

#

i mostly just write stuff for special effects

static lantern
#

I think the pursuit of perfect photorealism is a bit.. toxic?

heady iris
#

i do want to make some toon-y stuff

#

or maybe stealing some visual cues from Hi-Fi Rush

#

i love stealing visual cues

primal wind
#

Some games make realism their main point and forget about gameplay

#

Is it a game if it's not fun to play?

heady iris
#

i saw a tutorial for re-creating its Ben-Day dot bloom effect

static lantern
#

Like, go look at the CryEngine tech demo. They focus entirely on graphics. To be fair, that's their whole claim to fame, but there's almost nothing being shown off on the technical side. Oh, you can do ragdoll IK? Mkay.

heady iris
#

i can do ragdoll IK by falling out of my chair

static lantern
primal wind
#

The floor is underated

static lantern
#

Waiting for them to stop bitching that another game studio gave up trying to fix their engine before moving to Lumberyard.

static lantern
primal wind
#

It's been a few minutes without anyone needing help here

heady iris
#

devolving into madness

static lantern
#

It's not whether they need help, it's the kind of help.

primal wind
#

I honestly wonder if someday we'll get multithreading support

static lantern
#

Tbh this who chat is leaving me wanting for a gamedev shitposting community

heady iris
#

you just can't have 20 threads fighting a battle royale over the scene

rancid basin
#

hello. so i made climbing scripts for a VR game with gorilla locomotion and i currently have 2 problems.
the 1 one is that if i grab onto something my player is glitching weird (yes the rigidbody is kinematic) and the 2. problem is that if i grab onto a swinging object im not moving with it. i will send a video of how it looks like. appreciate any help.

static lantern
#

THERE IT IS

heady iris
#

jitter like that makes me think that some stuff is happening in fixedupdate and some stuff isn't

#

is interpolation enabled for the rigidbody?

rancid basin
#

i can send the scripts wait

heady iris
#

i'm not sure how that'd interact with VR

rancid basin
heady iris
#

i've only done like one game jam involving VR lol

rancid basin
#

these 3 scripts are handling the climbing. it may could be the problem of the gorilla locomotion

primal wind
#

I would make VR games and mod existing games into VR if i had a headset

rancid basin
heady iris
#

late update takes place after animation

#

i wouldn't expect that to matter otherwise

lean sail
#

Late update is typically just for camera movement

lean sail
# rancid basin

Are u able to post some of that code on a website, not downloading that on mobile
!code

tawny elkBOT
#
Posting code

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

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

static lantern
lean sail
#

I don't really get what you're doing with the fixed update last = transform.position,
Is your delta value anything other than 0?

#

It seems like if it is, its gonna be very unreliable to move the player consistently

rancid basin
lean sail
#

I see that, but is your delta value working for each frame?

#

I cant imagine that it does

#

Plus in your Move() you are multiplying by fixedDeltaTime which is just 1/50

#

But it's still being called in update

remote abyss
#

Hey guys and gals. So when I shoot at an enemy, the missile hits the target and the explosion which is in a gameobject container works. But, it is not destroying the effect or the light. Here is the code ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MissileController : MonoBehaviour
{
public float missileSpeed = 30f;
public Rigidbody rb;
public GameObject hitParticlePrefab;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    rb.AddForce(transform.up * missileSpeed);
}

private void OnTriggerEnter(Collider other)
{        
    Instantiate(hitParticlePrefab, transform.position, Quaternion.identity);
    Destroy(gameObject, 1.0f);          
}

}``` Is it because the effect is contained in a gameobject as a child and I have to delete the children? Thank you in advance for pointers please.

prime sinew
remote abyss
#

@prime sinew I thought once you destroy the main gameobject the effect's are children off they should all be destroyed?

prime sinew
fluid tapir
#

Hey guys, I am trying to implement layered animations in my animator using Animation masks. I am trying to create a combination of rifle put away and walk/run animations. For example, we can draw the rifle while walking or running. What I've done is:

  1. Base Layer: Consists of the idle/walk/run blend trees (for both with rifle and without rifle)
  2. Hand Layer: Consists of the mask for only hands and the animation where the player draws / puts back the rifle.

The issue that I am facing here is that when the animation for putting away the rifle finishes the hands of the character stay still for the animation it played using the Hand Layer. Is there any way to fix this ?

remote abyss
#

@prime sinew

#

the code is on the Explosion3 object

lean sail
#

What's the hierarchy after the parent is destroyed?

fluid tapir
lean sail
#

U shouldnt really have to. The children should get destroyed

#

We should look into why instead of hacky work arounds for something that should work

remote abyss
#

thats what I thought

lean sail
#

Show the hierarchy after its destroyed

#

I believe it might be related to the instantiate but not too sure

remote abyss
#

@lean sail can you elaborate not sure I follow you on "show the hierarchy after its destroyed" pls.

lean sail
#

U showed the hierarchy, show it again after destroy() is called

remote abyss
#

ahh ok

#

@lean sail hrm...

lean sail
#

Is your script on the right object

remote abyss
#

so it does destroy the explosion but not the main gameobject and other children. Script is on the main object the container Explosion3

lean sail
#

What is hitParticlePrefab

remote abyss
#

sorry the script is on the missile not the explosion3 my misstake

#

hitParticlePrefab is the explosion prefab

lean sail
#

ah i guess u have your solution then

remote abyss
#

ahh I see what I did wrong. Im destroying the hitparticleprefab from the instantiated missile prefab .

lean sail
#

Well idk which object is which unless u show the prefab, your script is just on the wrong object

#

Or you intend to call destroy on the parent

fresh widget
#

Hey guys. Something weird is happening in my Unity. Before I used to build apk for my game and test them out. I saw the option for patching so i pressed Patch. But it crashed my PC. So, I got back to just Building the apk. But now the Build process crashes my PC after 20 mins. It never took that long to build either. Please help. Its really urgent.

remote abyss
#

Yupp fixed it. Put a destroy(this.gameobject, 2.0f); on the explosion prefab and that solved the issue. hehe thx guys!

rancid basin
ruby fulcrum
ruby fulcrum
#

do that by changing its weight to 0

lusty dragon
#

Guys, I need your help,
I need to make the following code clamp between -90 and 0 degrees on the x but I cant help it

  private void FixedUpdate()
  {
    float angleY = 0;
    float angleX = 0;

    if (turning)
    {
      // Calculate the rotation angle and direction
      angleY = turnSpeed * Time.fixedDeltaTime * (turnRight ? 1f : -1f);
    }

    if (_tilting)
    {
      // Calculate the rotation angle and direction
      angleX = tiltSpeed * Time.fixedDeltaTime * (_tiltUp ? 1f : -1f);
    }
    // Apply the rotation on global axes
    transform.eulerAngles = new Vector3(transform.eulerAngles.x + angleX, transform.eulerAngles.y + angleY, transform.eulerAngles.z);
    
  }

Any implementation with Quaternions or something?
Whenever I use them z-axes gets disruppted as well!

fluid tapir
# ruby fulcrum disable the hand layer if your not using it

I kind of found a work around for that was to transition to an empty state for that layer after the draw animation is finished. I did think of resetting the weight of the layer to 0 but that will be too much code. Thanks anyways for your help 😄

rancid basin
sage kite
#

I'm using text meshPro and i got this weird bug that I don't understand, so basically I'm cloning an object, and when the cloned object is spawned the text is behind the bubble in my game view, but works completly fine in the scene view

#

scene view:

#

Game view:

#

Any ideas why?

potent sleet
#

this isn't a code question

sage kite
#

Aight

hollow hound
sage kite
#

or this

hollow hound
sage kite
#

it's 0 and i have tried -1 and 1

#

The thing is, it works before the cloning

#

here is the object that I clone in game view

open crystal
#

Hey all, I am attempting to use fishnet and XR Interactions toolkit, I am needing to change XR Interactions Toolkit scripts from Monobehaviors to NetworkBehaviors, however in any of the XR Interactions scripts, I am unable to use "using Fishnet.Object", and thus cannot change the script from monobehavior to NetworkBehavior. Any leads on what might be going on here? Is it something with the default assembly?

#

Xr Interactions toolkit scripts are in their own namespace, if that helps.

smoky sonnet
#

I'm moving my question here from #💻┃code-beginner :

I have a building system that allows you to freely place objects, and rn Im trying to make the colliders work. The issue is that the preview is always red (meaning it's colliding). The terrain has the Ground tag (which is layer 9) and the placeable objects have the Building tag. ```csharp

    if (Physics.CheckBox(_objToPosition.transform.position, bounds, Quaternion.FromToRotation(Vector3.up, hitInfo.normal), ~(1 << LayerMask.NameToLayer("Ground"))))
    {
        // Collides
        _objToPosition.GetComponent<Renderer>().material = _buildingMatNegative;
        return;
    }``` 

Somehow the above if statement still executes true even though the object to position is only hitting the terrain and nothing else.

#

I've been stuck with this a few hours now and it's driving me crazy

#

I've tried a lot of different things but none worked

#

The cube does have a collider

shrewd meteor
# sage kite

i know this isn't answering your question, but is this little guy based off punpun?

sage kite
#

Yup

sage kite
#

I want to be able to interact with him, but the text isent working

shrewd meteor
#

definitely knew i'd seen that somewhere, lovely blast of depression from the past 😭

shrewd meteor
sage kite
#

Most of the functionality works

#

Just need to fix this and make some more animations

orchid bane
#

https://pastebin.com/NQ99y9Xv
I have this piece of code which basically implements a grid but sometimes I have problems with removing an element from it.
You can see the debug and condition for it in the Remove method.
This is a typical debug message (almost always the same with exception of position) asd 0, 0, contains: False, wp: (-1.16, 0.00, 1.35), sameList: True, removed: False everRemoved: True, sometimes 0, 0 is something like 2,2
Next there goes ArgumentOutOfRangeException at the line with list.RemoveAt
Any ideas for why it may be so?

fast aurora
#

Is there any simple way to draw a boxcast?

#

For debugging purposes

orchid bane
fast aurora
#

What

#

That's my script

cold parrot
fast aurora
somber nacelle
fast aurora
#

well yes, but it doesn't say much on how to use the BoxCast

#

Do I replace the existing raycast?

somber nacelle
#

You can replace calls to Physics and Physics2D methods with DrawPhysics and DrawPhysics2D to simply draw the results of a physics operation.

languid hound
#

Just hypothetically is there a way to detect input via script with the new input system? Like no bindings just like DetectInput GenericGamepad/Whateveryayayawdhiaduawidh?

somber nacelle
languid hound
#

Oh hell yeah! Thanks

#

I don't know why I didn't think of looking at the docs

somber nacelle
# fast aurora Do I replace the existing raycast?

oh also, if you want it to be easier, you could use the using alias suggested in the Code stripping section of that same Usage description. This is what I typically do so I don't have to worry about remembering to use DrawPhysics2D instead of Physics2D when using multiple queries in the same class

round palm
#

Hey guys, I need help with something. In my game the camera follows the player by having the exact x and y position as the player every frame, so no lagging behind and catching up. I want the camera to cut off at a certain part of the room (which I have done) and only allow the player to move (with the camera) to the rest of the room after the player has touched a certain object. However, if I immediately set the camera position to the player position once the player touches the object, it will be a hard cut and be jarring. Rather, I want to animate the camera to return to the player, then to resume its previous movement of matching the player's position. I am trying Vector3.Slerp for the animation, but I can't seem to get any code to work. Ideas?

hidden compass
#

Cinemachine

#

it does that for u automatically

round palm
#

how do I implement that

hidden compass
#

when u disable one VirtualCamera, and enable another, it'll smoothly translate

#

if u dont want to use cinemachine u can Lerp the camera to the new position

hidden compass
#

in the package manager you can install Cinemachine...

#

its a unity package..

#

and then use 1 camera

#

have it whereever u want it.. and create 2 virtual camera's

round palm
#

thanks

hidden compass
#

when u wnt it to be stationary.. u switch to the VCAM without the follow code

#

and then disable it and enable the camera WITH the follow code

#

it'll automatically transition

atomic matrix
#

why is my visual studio white and errors dont have the red underline and there is no minimize or maximize buttons in top right?

heady iris
#

visual studio machine broke

#

that is an interesting graphical problem

#

i'd restart your computer first

atomic matrix
#

this happened like a week ago ive just been trying to deal with it

hidden compass
#

and the one with the higher priority will be the one it transitions to.. u can see here the camera im messing with is just there.. the other camera is attached to the player controller..

#

not even needing to mess with that one..

#

what it does is.. the virtual camera acts as a place holder.. for where the main camera is positioned

#

main camera just gets the cinemachine brain component

round palm
#

cool

#

I really appreciate the explanation

simple egret
edgy lynx
#

Which I just made into an event:

    private void InputActionChangeCallback(object obj, InputActionChange change)
    {
        if (change == InputActionChange.ActionPerformed)
        {
            InputAction receivedInputAction = (InputAction)obj;
            InputDevice lastDevice = receivedInputAction.activeControl.device;
            _isKeyboardAndMouse = lastDevice.name.Equals("Keyboard") || lastDevice.name.Equals("Mouse");
        }
    }
sage kite
#

Is there a smart way to spawn in a clone but as a child for the Parent?

simple egret
#

Some overloads of Instantiate take a Transform as last argument, the Transform it will be parented to.

languid hound
languid hound
#

Does anyone know how I could possibly add a 1D composite binding? Trying to detect D-Pad up and down only and I cant seem to find much on specific paths for bindings

simple egret
#

Why not just create an Input Actions Asset, then create it in code and bind to events? That's still a full code solution

west elk
#

Hi! I'm making a classic card game, is it worth making each card an ScriptableObject? or just a class and generate the deck is enough?

willow hull
#

Quick Question : is it a bad idea to send from the server a json which inside include the list of all the characters of the player and their stats to the client? using tcp

somber nacelle
neon plank
#

I have a Unity job which does something like:

nativeArray[i * 3 + 0] = GetOne();
nativeArray[i * 3 + 1] = GetTwo();
nativeArray[i * 3 + 3] = GetThree();

But I get:

IndexOutOfRangeException: Index 65 is out of restricted IJobParallelFor range [21...21] in ReadWriteBuffer.

How should I solve it?
I noticed that a simple nativeArray.AsSpan() disables the Unity safety checkings... should I do that?

neon plank
#

But my code is guaranted to not collide read/write in the same element.

leaden ice
neon plank
#

Ok

steel bronze
#

Quick Question: how do I set up a check to see if an object is on another object, like a box on a button, to play an animation?

leaden ice
heady iris
#

like, a collision?

leaden ice
#

like a crate touching a physical button, portal style?

steel bronze
#

ya, similar

leaden ice
#

and vice versa

steel bronze
leaden ice
#

Yep the drone obviously isn't relevant was just giving the video due to my button

carmine cloud
#

I have a 2d character I'm working with, when it was set up it was only given 1 large collision box that was used for both hit-scanning and for world movement collision. I'm assuming it was set up that way because collision boxes are components in unity and a script can really only address one collision box at a time.

I'm wondering what would be the best way to go about setting up several collision boxes like I've drawn. I've done this before in another engine, but there collision boxes were objects not components so it was fairly straightforward to pull all of them into one script.

heady iris
#

when a collision event occurs, all components with the appropriately named methods will get that method called

#

i'd just put them on different objects, and put components on those objects to handle the events

glad sentinel
#

Okay so peep this: I want to make a bestiary in my game but I'm not super sure of the best way to go about it.

Essentially it'd be a book that would slowly fill over time as you meet new creatures, obviously the UI would be a different matter, I'm just not sure of how I would get this done - or am I just looking too deep into it and would it just be a case of a LOT of triggers?

I have a decent idea of what I want, I just need to iron some stuff out

carmine cloud
heady iris
#

yes, you should separate them out by layer

#

this also requires that they are on separate objects

heady iris
#

i'd start with just displaying all of the enemies

#

figure out that interface first

#

then worry about hiding ones you haven't found yet

carmine cloud
#

for the separate objects I should just use empty objects nested inside my character?

heady iris
#

ye

#

you might have several hitbox objects parented to different things

carmine cloud
#

just seeing them could be a ray cast or a really large trigger collider, combat could be registering a hit or damage on them, death could be interacting with a trigger collider that's enabled on their corpse, there are tons of different approaches.

glad sentinel
#

Bet, thank you kindly

steady moat
carmine cloud
fiery jackal
#

Hey everyone, I have a question about the CombineMeshes. I combined a few hexagon planes, it created a single mesh, but it still behaves as if each of the hexagon is a separated object when I apply my Shader that moves the normals. Shouldn't it merge the common vertices into one?

topaz ocean
#

is there a practical means to destroy all components on a gameobject except the transform with consideration for requiredcomponents?

steady moat
steady moat
fiery jackal
topaz ocean
#

Seems to work, and I can only see this failing if unity changes the order in which dependencies are added to an object.

steady moat
topaz ocean
#

what is that

round palm
#

Anyone here well versed in Cinemachine?

formal coral
#

Does anyone know how to set the default code that is set when you create a new c# script

formal coral
#

ty

empty pelican
#

MissingReferenceException, I need help

marsh hawk
#

If anyone knows, how would I make an image flash on screen using UI, then the image fades out slowly?

somber nacelle
#

to make it fade out, just lerp the alpha on its color property

velvet pebble
#

or make an animation

limpid siren
#

Hey guys.

Im doing a jump system and a horizontal move using mobile rotation.

Jump works by clicking once or clicking and hold to jump higher.

When i created the horizontal function the jump holding is not working anymore.

Flux:

        private void Update()
        {
            if (!isAlive)
                return;
            this.playerJumpInput = Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0);
            this.playerJumpInputUp = Input.GetKeyUp(KeyCode.Space) || Input.GetMouseButtonUp(0);
            this.playerJumpInputDown = Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0);
            if (this.playerJumpInputDown && (IsAnimatorReady() || isSwinging)) isGoingToJump = true; // Jump from ground or vine
            isFalling = (this.playerRigidbody.velocity.y < -0.1f) ? true : false;
            if (this.playerRigidbody.velocity.y < -10) isRolling = true;
            AnimatorHandler();
        }
        private void FixedUpdate()
        {
            if (!isAlive)
                return;
            if (!isSwinging)
            {
                this.MovePlayer();
            }
            else transform.position = currentVine.transform.GetChild(0).position;
            if (this.isGoingToJump && this.IsPlayerGrounded()) this.Jump();
            if (this.isGoingToJump && isSwinging) this.JumpFromVine();
            if (this.playerJumpInput && isJumping) this.JumpHigher();
            if (this.playerJumpInputUp) this.StopJump();
            if (isJumping && this.playerRigidbody.velocity.y < 0f && this.IsPlayerGrounded()) isJumping = false;
            HorizontalMove();
        }
#

Jump Code:

        private void Jump()
        {
            Debug.Log("Start Jumping");
            isGoingToJump = false;
            this.playerRigidbody.AddForce(Vector3.up * this.jumpForce, ForceMode.Impulse);
            isJumping = true;
            isRolling = false;
            jumpTimeCounter = jumpTime;
        }
#

Horizontal move:

        private void HorizontalMove()
        {
            var dirZ = Input.acceleration.x * 20f * -1;

            float speed = Mathf.Clamp(dirZ, -20.0f, 20.0f);
            Vector3 vel = new Vector3(this.playerRigidbody.velocity.x, this.playerRigidbody.velocity.y, speed);

            Debug.Log("vel: " + vel);
            this.playerRigidbody.velocity = vel;
        }
#

So i think the problem is that im using add force to jump

somber nacelle
#

it's cs to format for c# syntax highlighting. also use a bin site to share large blocks of code

limpid siren
#

and when i do the horizontal move and set the velocity of y it stops the impulse

mossy valley
#

Nvm, the fix was to move it to the Editor folder, it worked!

rancid pollen
#

hi, might be a silly question, but i'm just wondering if there's an efficiency difference (or at least a preference) between

class A
{
    B b;    // assume no nullref    
    void Method()
    {
        StartCoroutine(b.DoSomething());
    }
}

and

class A
{
    B b;  
    void Method()
    {
        b.StartCoroutine(b.DoSomething());
    }
}
orchid bane
#

When I try to install my project as apk on Bluestacks it says the version is inappropriate even though it was fine before. I switched to IL2CPP. Any ideas?

lean sail
woeful slate
#

I have a 2D top down game. I'm using TileGrid (so many layers kekwait ) to create the landscape, but I want to allow the character to use a shovel to expose dirt, and then expose a hole sprite. Would that mean every tile needs to be a game object?

cosmic rain
orchid bane
#

Is burstCompile useful to put on functions which aren't jobs?

cosmic rain
orchid bane
#

There aren't any collections in my function

#

But there are only structs

#

What do you think?

cosmic rain
#

I mean, you can try and see for yourself.🤷‍♂️

orchid bane
#

Doesn't hurt I guess

visual fractal
#

I got this code off the Unity Marketplace.

#

It's the Modular First Person pack, so the code should be working. Could it be because I'm in a newer version of Unity?

cursive moth
visual fractal
#

I think so.

#

Let me check.

cursive moth
#

code does indeed seem fine but I am quite tired so chances are I am missing something

visual fractal
#

Inspector seems fine. If you're tired, then I'll stop bothering you if you want.

cursive moth
#

I am just saying that there is a chance I'll miss something crucial

#

did you setup the object as the creator of the asset intended?

#

and also, are you getting any errors in the console?

visual fractal
#

I used the player object that was provided in the pack, and the error is NullReferenceException: Object reference not set to an instance of an object FirstPersonController.FixedUpdate () (at Assets/ModularFirstPersonController/FirstPersonController/FirstPersonController.cs:425)

#

I don't see anything wrong with line 425 in the script, though.

cosmic rain
visual fractal
#

It's just something to do with the sprint bar that I have disabled.

cosmic rain
#

Debug the references on that line to find out which one is null.

cursive moth
#

remove that line

#

I mean those lines

cosmic rain
visual fractal
#

It shouldn't make it not work, though.

#

I'll try.

cursive moth
cursive moth
cosmic rain
visual fractal
#

Now there's this error. Assets\ModularFirstPersonController\FirstPersonController\FirstPersonController.cs(520,1): error CS1022: Type or namespace definition, or end-of-file expected. There is absolutely nothing wrong with line 520. It's just a }

cosmic rain
#

Or added one extra

visual fractal
#

It's the end of the script, though. Should there be anything other than a squiggly bracket?

cosmic rain
#

Although that's just an assumption. It could be some other syntax error. Impossible to tell without seeing your code...

visual fractal
#

Ok, I fixed every error except one, and I don't understand it. Assets\ModularFirstPersonController\FirstPersonController\FirstPersonController.cs(436,5): error CS8803: Top-level statements must precede namespace and type declarations.

#

This is the line of code it's talking about: void CheckGround()

woeful slate
wide terrace
visual fractal
#

I don't think there are any misplaced brackets, and this void is in the same place relative to the rest as all the other voids. ```void CheckGround()
{
Vector3 origin = new Vector3(transform.position.x, transform.position.y - (transform.localScale.y * .5f), transform.position.z);
Vector3 direction = transform.TransformDirection(Vector3.down);
float distance = .75f;

    if (Physics.Raycast(origin, direction, out RaycastHit hit, distance))
    {
        Debug.DrawRay(origin, direction * distance, Color.red);
        isGrounded = true;
    }
    else
    {
        isGrounded = false;
    }
}```?
lean sail
#

also show where your IDE underlines an error

wide terrace
visual fractal
#

Ah.

#

Thanks.

lean sail
# limpid siren can anyone help me here?

your code is hard to read on discord, but you should add debugs to see what input exists at once. Like if your jump holding gets canceled by pressing horizontal movement. I dont see any specific issue with your HorizontalMove

#

also pls format your code to be more readable, it may seem concise to you for anyone else its difficult to read

lean sail
limpid siren
#

i fixed it hardcoding a instant velocity when jumping instead of just waiting for the impulse force eheh

#

now im dealing with a situation

#

why velocity got stoped everytime it is colliding with a wall?

#

or any other object

#

i want it to keep falling, even if it is colliding with a wall

#

i just want it not to go trough the wall

lean sail
limpid siren
lean sail
#

if you want it to slide off the wall then u need a frictionless material

#

u can create a physics material and just set it to 0 then put it on the colliders

limpid siren
#

perfect bro

limpid siren
indigo haven
#

Hey good day.
I have a dijkstra matrix (chess board with numbers representing distance from a point to that square) and i wanted to make a color gradient using that info, is there any way of doing so without needing materials for each distance nor shaders?

mental rover
#

iirc there's a problem with it in that you can't batch materials if you use it, which sort of defeats the entire point of the optimisation, so perhaps there's something better out there

indigo haven
#

I will, thanks. And dont worry i dont care to much about optimization for now

grand vortex
#

Hi why is CharachterController.isGrounded is not reliable and is there a solution 4 it

lean sail
lyric panther
#

Is there a way to have different camera use different quality levels? eg one camera renders on low and one renders on high. trying to do a LOD kinda thing where portal screens render in lower quality when they're further away

spring basin
#

Hello good day, I have a game which has multiplayer in it using Netcode for GameObjects. I used to make the server build and the client build from the same project. This used to work when the project initially had no other third party plugins but I went ahead and added mediation and what not to the project, without thinking about how it could effect the server build. Now, I am unable to make a server build specifically a linux server build since plugins like AppLovin (an adk sdk) don't support these platforms. How do I salvage the project now? Also, how do you guys handle server/client architectures and third party plugins? Thank you for your input

severe maple
#

I keep getting MOVING FILE FAILED - access denied errors when I attempt to open my unity project after a format. 5 years of work gone? Have rebuilt temp/library folders still same

thin aurora
simple egret
#

What do you mean by "after a format"?
Just pull the latest version from Git. If you haven't made backups in 5 years then that's on you

severe maple
#

I have the latest backup. I had to reinstall windows on a new drive, along with unity and hub. Tried to load my project (different HD) and get errors as above

simple egret
#

Unity may not have sufficient rights to move files. Try running it as administrator and see if that fixes the issue. Also check your Hub configuration, it might be trying to move files from folders that don't exist anymore