#💻┃code-beginner

1 messages · Page 6 of 1

solar tide
#

I'm doing an array movement of a card(that functions like a chesspiece on a chessboard)
I tried to hard to do this alone by just looking at tutorials but it's so hard because what I want is so specific

#

So, I have the card, and when the button that is attached to the card is pressed, it moves forward 1 space on the Vector2Int array.
I made the array from a chess making tutorial but our ways diverged and it's getting hard.

rich adder
solar tide
oblique ginkgo
#

hatebin good lord

rich adder
eternal falconBOT
#
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.

solar tide
#

These are my scripts. In gameboard, look all the way down to moveforward and moveforwardpart2

#

It's declaring a null reference.
I made a script that selects a game object you pressed and wanted to make the selected card move forward 1 space in a grid.
But I think I'm really struggling on transforming the raycast hit.transform to a grid []

rich adder
#

I can't even see the scripts so 🤷

solar tide
solar tide
rich adder
oblique ginkgo
# solar tide 270

So its either RubyRose or unit that are null. Go ahead and debug log or debugger check them

solar tide
solar tide
rich adder
oblique ginkgo
rich adder
#

avoid Find Methods :\

oblique ginkgo
rich adder
#

could be
is highlight a transform ?

solar tide
#

I think their both null

oblique ginkgo
#

Okay yeah they are both null

#

Lets look at rubyrose first

#

Are you sure highlight is not null?

rich adder
#

is highlight a transform ?

oblique ginkgo
#

You can check this with your inspector on debug mode and play the game

rich adder
#

huge difference between GameObject.Find vs Transform.FInd

oblique ginkgo
rich adder
#

then be aware transform.Find only looks for children

oblique ginkgo
#

That is assuming highlight isnt null in itself, your assignment of highlight is in an if statement so it might never get assigned

rich adder
#

true

#

but if it isn't then its looking in the wrong spot too (possibly)

#

we need to also see the hierarchy

solar tide
#

Highlight is not null

oblique ginkgo
#

wait what the hell

rich adder
oblique ginkgo
#

whatd you change the debuglog to?

#

your hierarchy architecture is confusing
anyway okay if its not null then yeah, hierarchy

solar tide
oblique ginkgo
#

Screenie your hierarchy

#

With all children shown

#

'exposed' is not the word in that sentence

solar tide
rich adder
oblique ginkgo
#

Okay so your highlight object is the gameobject named RubyRose

oblique ginkgo
#

so your code is looking for a child under RubyRose named RubyRose

#

is that what you intended?

rich adder
#

yikes

oblique ginkgo
rich adder
#

if its on the same object just [SerializeField] it

rich adder
#

if you must use runtime search (for spawned runtime objects) then use Tags.

#

or components

solar tide
#

I actually wanted to move the highlighted object 1 tile forward on the array.
I originally did do highlight.position but it also kept calling null, specifically on the part where it says = unit.transform.position

solar tide
#

I got rid of find since highlight is RubyRose

rich adder
#

you have a lot of Finds lol

solar tide
#

finds as in, Genunit unit and int x etc?

#

Inside the () of the method?

#

Oh, you mean up there?

rich adder
#

all the menu stuff

queen adder
#

transform.rotation = Quaternion.Lerp(transform.rotation, ReferenceHolder.Instance.characterReference.FOW_Revealer_Rotation, Time.deltaTime * multi);What does this error mean?

solar tide
#

Do you know a way to make it perform better?

rich adder
#

it talks about this

#

and alternative better ways

queen adder
rich adder
#

(i genuinely don't know sorry)

oblique ginkgo
#

one of your quaternions is (0, 0, 0, 0)

#

otherwise known as undefined

queen adder
#

oh

#

yea that can be the problem since the revelaer roataion is using a blank quaternion

keen dew
#

Also you're using lerp wrong

oblique ginkgo
#

this is how you do smooth movement with lerps

keen dew
#

ya rly

#

You shouldn't try to do smooth movement with a lerp

oblique ginkgo
keen dew
#

That's not a valid reason to do it

queen adder
#

i want my rotation to move fast when player look at opposite direction

#

im fine with a lazy lerp for this one

rich adder
#

wouldnt quaterion.slerp be better ?

queen adder
#

probably change into that one

oblique ginkgo
#

It's still an approach you can use, it will yield an okay result depending on what you consider okay

queen adder
#

nvm, lerp is better

#

wont slep be more unpredictable?

#

how to know which direction it will decide to turn?

oblique ginkgo
#

slerp gives you an ease in ease out, while lerp is linear this looks infinitely more complicated than what i know

#

direction seems irrelevant

keen dew
#

How do you know which direction lerp will turn?

ivory bobcat
#

Broken lerp is usually associated with an inconsistent source

#

And constant/random point in interpolation:cs Lerp(source, target, point)

dark berry
#

🤓 "Your using Lerp wrong."

rich adder
dark berry
#

That really got me

rich adder
#

ya the spelling funny

unreal imp
#

hey, do any of you know how it would be possible for an object to have cracks that mean it is going to be destroyed? (eg: if you saw Minecraft, the iron golem also presents those cracks that signify its life point and each time it is lower, the more cracked it appears)

polar acorn
solar tide
#

I don't know how to call the game object child itself despite watching many tutorials. GetComponent always gets the component of an object but never the object itself through name, right?

#

So how am I supposed to change my "find" functions with getcomponent

ivory bobcat
polar acorn
rich adder
unreal imp
#

upss sorry

solar tide
#

I've also seen this way of getting children but it gets every single children, surely this can't be the answer

polar acorn
solar tide
#

which is why I used find

polar acorn
valid finch
#

How do I make two scripts send information to each other? I want to send information to another script from my method

polar acorn
solar tide
#

I need to access the child of an object that is being highlighted after I click on it with a mouse.
The script for the ray that highlights the object is not inside the object itself

uncut dune
#

can I change a setting of a material to only one of the gamobjects that is using it thru script?

wintry quarry
polar acorn
#

is it instantiated there, is its parent set, or what

wintry quarry
polar acorn
unreal imp
#

ok I will change to something simpler, is there any method or way to detect if my object has an impulse type force in its rigid body but with a certain speed? I only find addForce

polar acorn
#

Are you asking how to check if the velocity is over a certain amount?

#

You can get the magnitude of the velocity and check that

unreal imp
#

yeah but with a certain type of mode

#

in my case i already say Impulse xd

polar acorn
#

The ForceMode determines how the force is added to the velocity

#

there's not different "types" of velocity

unreal imp
#

😦

#

wait

#

that was because I was trying to imitate the GMOD's explosive barrels, they act like this: if the player collides with them while they are against a wall they do not explode (unlike my case where they do) and also if they fall from a great distance,the only thing that makes them explode is a type of force that is when you use the gravity gun or let another barrel explode next to it

#

I will send comparison video

rich adder
#

they probably just check a certain threshold for velocity on impact

polar acorn
#

Or just set a flag like can_explode when you fire it

unreal imp
#

mmm you two gave me an idea

valid finch
#

For an example..

Script A is attached to GameObject 1
Script B is attached to GameObject 2

Within ScriptA I make a public GameObject pointing to GameObject 2

Within ScriptB I make a public GameObject pointing to GameObject 1

Is this the proper way to set this up?

#

This way they can share variables and update each others variables correct?

wintry quarry
rich adder
wintry quarry
#

Using GameObject just adds complication to your code and makes it more prone to accidental errors when assigning them in the inspector

polar acorn
#

Why bother dealing with the GameObjects when you actually want the scripts

valid finch
#

Alright good point

#

thank you all

wintry quarry
valid finch
#

That is a better way to put what I wanna do

#

public Scriptable path

#

or what is the way to reference a script

polar acorn
valid finch
#

Or scriptableobject

wintry quarry
valid finch
#

Oh ok. I can directly reference the script name
Public FootballController name

valid finch
#

Thanks everyone. Back to work. I appreciate it

elfin eagle
wintry quarry
#

neither circled line can possible throw that error

#

the error will have a filename and line number

elfin eagle
wintry quarry
#

you earlier said they're attached to different objects

elfin eagle
#

ohh ok

wintry quarry
#

also .GetComponent<Transform>() is NEVER needed

#

you can just do .transform

wintry quarry
elfin eagle
wintry quarry
#

in this example it seems like it's an enemy you're spawning

elfin eagle
elfin eagle
wintry quarry
elfin eagle
#

alright then ill try that

#

thx

jagged gulch
#

Having some issues with my shotgun. I have it setup to create bullet holes when a raycast I fire off hits a target. However, when I mash the fire button, the bullet holes get created before the animation goes off.

#
            {
                isFiring = true;
                ammoClipLeft -= 2;
                Debug.Log(isFiring);
                cameraBobbingScript.enabled = false;
                lastPos = cameraPos.localPosition;
                cameraPos.localPosition = startingPos;
                //source.PlayOneShot(shotSound);
                GunFiringAnimation.SetBool("aniTrigger", true);
                DynamicCrosshair.spread += DynamicCrosshair.shotgunSpread;

                for (int i = 0; i <= numOfPellets; i++)
                {
                    Vector3 direction;
                    Vector2 randomSpread = Random.insideUnitCircle * spread;
                    direction.x = randomSpread.x;
                    direction.y = randomSpread.y;
                    direction.z = 0;
                    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition + direction);
                    RaycastHit hit;
                    if (Physics.Raycast(ray, out hit, shotgunRange))
                    {
                        Debug.Log("Shot has collided with " + hit.collider.gameObject.name);
                        hit.collider.gameObject.SendMessage("GunHit", shotgunDamage, SendMessageOptions.DontRequireReceiver);
                        Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
                    }
                }```
rich adder
#

cute graphics

timber tide
#

check your bool that it's not being switched too early

wintry quarry
jagged gulch
wintry quarry
jagged gulch
#

when the animation is finished (or triggered by an animation event near the end of it I have setup)

wintry quarry
#

right - show how you have that set up

jagged gulch
#

sure

#

I dont wanna move the event any earlier because then it makes the animation look jank

#
    {
        GunFiringAnimation.SetBool("aniTrigger", false);
        isFiring = false;
        Debug.Log(isFiring);
        cameraPos.localPosition = lastPos;
        cameraBobbingScript.enabled = true;
    }```
maiden charm
#

so ive been following this guide but i seem to have a error on the last }

jagged gulch
#

enemy sprite is just a basic one Im using for debuggin/setup

#

but yeah Im not sure what to do here, on the one hand, I dont wanna set it up so the animation ends too early. On the other hand, I want it setup so the bullet holes dont get instantiated too early

jagged gulch
#

really happy with how it turned out! Using this project as a proof of concept for myself for something Ill work on after Im done with my last project

short hazel
#

And yours, on line 47

rich adder
#

yup, you made a nested method

wintry quarry
#

Are you sure none of them are accidentally doing it early?

jagged gulch
#

that or control gun variables like ammo and recoil

#

nothin that would create the bullet holes

#

just a bunch of really simple methods for the animator to call to make the gun sound/play good

timber tide
#

Perhaps execute the firing function at a specific frame for your gun animation?

#

Because it's doing it on the first frame of the gun it seems, no?

jagged gulch
#

thats what Im thinkin

#

lemme give it a go

wintry quarry
jagged gulch
#

Thanks again! UnityChanThumbsUp

timber tide
#

ye

sharp flower
#

Hi, I'm using a rigidbody for my first person controller. I want to have it interpolate as it helps smooth when moving and looking (objects are jittering when interpolate is off) but when interpolate is on I can get this weird "feedback" effect that never stops. Any ideas why or how to fix it?

maiden charm
#

so they've matched up line for line but that last 41 is still red and errors

short hazel
#

Class declaration opened by a { right after class PlayerController : MonoBehaviour on line <unknown, cropped out>

valid finch
#

what would be the purpose of having a public void over a private void?

short hazel
#

Public means accessible from outside the class

#

So you would be able to call the method (not called a "void") from another script

valid finch
#

O ok, so if I want to use a method in another script I need a public method

short hazel
#

(void is the return type, meaning the method does not give a value back to you)

#

Correct

valid finch
#

even if the script is referenced like
public PlayerController playerController; // PlayerController Script

#

I have that in my other script to point to the player controller script

short hazel
#

Yes, the access modifiers you put on the variable here, are separate from the one you put on the method
In some case you'd still want parts of your script to be accessible from the outside, others kept private

valid finch
#

so is it bad practice to always just use public methods?

#

and they were public that wouldn't work out

wintry quarry
timber tide
#

It's kinda something you learn upon. If you're not too sure, keep it public honestly.

wintry quarry
#

there's lots of things you will want to be able to do internally in a class that you don't want to expose to the rest of the program

short hazel
#

When you don't want them to be accessible from the outside is one

wintry quarry
#

There's a reason private is the default access modifier

short hazel
#

Like, you don't want anything that has access to the player script to be able to call Die() on it

valid finch
#

true

#

good points

#

alright, I was just curious. Thanks

timber tide
#

Then you've got languages like python where it's not really enforce, so you're usually having to modifiy variable names, which is why you may see underscores before them in some context.

valid finch
#
public class FootballController : MonoBehaviour
{
    public GameObject football; //The football
    public GameObject following; //Follow the player with the football
    public PlayerController playerController; // PlayerController Script



    void Update()
    {
        Pass();
    }

    public void Pass()
    {

    }

}

So I pointed to the player controller script. How do I call a method from that script within a method in this one?

safe radish
#

why am i getting this error for a public void in a public class?

short hazel
short hazel
short hazel
# safe radish ahh i see ty

If the enum is meant to be used outside the class it was declared in, consider taking the enum out to its own file.

#

It's a type after all, like classes or structs

valid finch
#

Lol got my first stack overflow error ever.

maiden charm
#

managed to get the code to complie now with no errors. but doesnt seem to move the character

valid finch
#

Thanks for the assistance got the scripts working together now.

short hazel
#

Be glad Unity catches those, in regular C# app, a stack overflow terminates the process (hard-crashes the app)

valid finch
#

Is there a quick code cleanup button to fix my formatting

#

within visual studio that you know of

short hazel
#

Ctrl K, Ctrl D

#

It's a chord, press the first combination, release, press the second

valid finch
#

Thank you

vernal thorn
#

when i try too make a custom cursor in build settings i get Failed to set the cursor because the specified texture ('Rat Cursor') was not CPU accessible.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

#

and idk how too fix that

dusk musk
#

Hi everyone! Can someone help me with an issue I'm having with my game? My game is displaying a text GameObject that tells the player when a powerup is available. This text disappears when no powerups are available. However, when my plaer completes the game by achieving a target score, this text GameObject should also disappear. I have used this part of code for that:

        //Powerup availability
        if (GameObject.FindGameObjectWithTag("Powerup Pickup") == true && (player == true))
        {
            powerupPickup.SetActive(true);
        }

        else
        {
            powerupPickup.SetActive(false);
        }

But for some reason, the text continues to show when my GameComplete script runs. When my GameCompelte script runs, the player is set to false.

Here is the full script, and a video showing my issue: https://gdl.space/ewivujizib.cpp

Thank you for helping!

ivory bobcat
wintry quarry
wintry quarry
#

Also if you already have a direct reference to the object: powerupPickup what's the point of using GameObject.FindGameObjectWithTag("Powerup Pickup")??

dusk musk
dusk musk
dusk musk
ivory bobcat
#

Cache the cloned instances, if needed.

wintry quarry
#

Maybe you can back up and explain when this code is meant to be doing

limpid dawn
#

float x = Input.GetAxis("Horizontal");
camHolder.rotation = Quaternion.Euler(camHolder.rotation.x, camHolder.rotation.y, x * rotateForce * Time.deltaTime);

    if (x == 0) { camHolder.rotation = Quaternion.Euler(camHolder.rotation.x, camHolder.rotation.y, 0f); }

is there anything wrong with t his

verbal dome
orchid trout
#
    {
        ringMesh = new Mesh();
        GetComponent<MeshFilter>().mesh = ringMesh;
        CreateRing();
    }```

I am creating a mesh through code, there is no mesh in the project file that its looking at or pointing at, however every instance of this component writes to the 'same mesh' as in they arent instanced per component, changes to one changes the other 🤔 How do I correctly make the meshes independent?
verbal dome
limpid dawn
verbal dome
limpid dawn
verbal dome
#

You never said what the code is supposed to do

limpid dawn
orchid trout
#

I don't know why though

#

why are none of these ever being called in editor?

#

ive been debugging this for four hours so my brain is just shot

verbal dome
#

If you want it to work outside of play mode, that is

#

Remember to Destroy any leftover Mesh objects so they dont stay lingering in the memory. Also Mesh.Clear() on an existing mesh is way faster than creating a new one

#

(In edit mode you should use DestroyImmediate)

valid finch
#
private void OnTriggerEnter2D(Collider2D collider)
{
    if (collider.CompareTag("Football"))
    {
        thisAnim.SetBool("hasBallAnim", true);
        Debug.Log("Picked up football");
        football.SetActive (false);
        footballFollowing.SetActive(true);
    }
}

How do I add a delay between football and footballFollowing

yield return new WaitForSeconds(duration); gives an error.. is there another way to go about this

slender nymph
#

you would need to use a coroutine if you want a delay

valid finch
#

so put this code within a coroutine and put that in the update?

slender nymph
#

you can just put the line you want delayed into a coroutine right after a yield and just start the coroutine right there in OnTriggerEnter2D where that line is currently at

valid finch
#
{
    if (collider.CompareTag("Football"))
    {
        thisAnim.SetBool("hasBallAnim", true);
        Debug.Log("Picked up football");
        football.SetActive (false);
      coroutine here
    }
}

The coroutine
yield return new WaitForSeconds(5);
footballFollowing.SetActive(true);

#

like that?

languid spire
#

not coroutine here but StartCoroutine here, but otherwise, yes

valid finch
#
IEnumerator PickedUpFootball()
{
    yield return new WaitForSeconds(2);
    footballFollowing.SetActive(true);
    Debug.Log("Picked up football");
}
private void OnTriggerEnter2D(Collider2D collider)
{
    if (collider.CompareTag("Football"))
    {
        thisAnim.SetBool("hasBallAnim", true);
        
        football.SetActive (false);
        PickedUpFootball();
    }
}

Worked just gotta fixed up my logic.

verbal dome
languid spire
#

no,
StartCoroutine(PickedUpFootball());

verbal dome
#

Otherwise it will either stop at the yield, or skip the yield, I forget which

valid finch
#

Ok. I trust you. Just like to know the reason behind doing what I'm doing

#

Ok, got you

languid spire
valid finch
#

haha fair enough

oblique gazelle
#

hello i need help with unity switch weapon

grave jay
#

how can i try to find information1, 2, and 3 using i to find the public value in this gameobject?
Cardchosen is the card on the first screenshot

rich robin
polar acorn
polar acorn
grave jay
upper spire
#

could anyone give me some pointers on how to code a drawing system in unity please?

short hazel
#

drawing_system *ptr;

#

Jokes aside, probably with a texture modifiable from the code at runtime

summer stump
rich robin
upper spire
rich robin
upper spire
limpid dawn
grave jay
#

because what im simply trying to do is trying to type information1 using i2, kinda like you would normally do with 2 strings using a +, idk how i would do it here tough

summer stump
grave jay
summer stump
#

Simply put, don't do it with string concatenation... that is a terrible way to do it

grave jay
#

Wait

#

so you mean make a public array in the scriptableobject?

grave jay
#

Huh, i didnt know you could do that

#

yeah that would work, thanks!

limpid dawn
#

can anyone help?

summer stump
#

Show code

limpid dawn
#

i gave you the problem up there

rich adder
limpid dawn
#

the vid?

summer stump
rich adder
limpid dawn
#

private void FixedUpdate()
{
//Rotate camera in the direction the player moves in
Vector3 rot = camHolder.eulerAngles;

    float x = Input.GetAxis("Horizontal");

    rot.z = Mathf.SmoothDamp(rot.z, x * rotateForce, ref velocity, smooth);

    if (x == 0)
    {
        camHolder.rotation = Quaternion.Euler(camHolder.rotation.x, camHolder.rotation.y, 0f);
    }

    camHolder.transform.rotation = Quaternion.Euler(rot);
}
rich adder
limpid dawn
#

??

rich adder
#

you don't want to compare floats with ==

limpid dawn
#

hm

#

so wat shold i do

#

..

#

hmm

#

i cant find any problem

rich adder
#

find a better camera rotation script 🤷
idk rotations too well

limpid dawn
rich adder
#

also why rot.z

limpid dawn
ripe nymph
#

Hey everyone, i'm trying to change the offset in a cinemachine camera through script, i can't seem to access it though?

#

I'm stuck on this so not sure what to do

#

Ooooh i might have it actually

jagged gulch
#

Back again, got another question. So Im working on a simple recoil system for my gun in Unity, but want it to be different. My current implementation has it return to the postion from when the gun was fired (like most recoil tutorials I've checked have it do), but Im more looking to add in a system that knocks the camera rotation up and around with a procedural generated num instead.

#

I feel like its easy but Im having a hard time wrapping my head around it

#
    private Vector3 targetRot;

    [SerializeField]
    private float recoilX;
    [SerializeField]
    private float recoilY;
    [SerializeField]
    private float recoilZ;

    [SerializeField]
    private float snappiness;
    [SerializeField]
    private float returnSpeed;

    void Start()
    {
        
    }

    void Update()
    {
        targetRot = Vector3.Lerp(targetRot, Vector3.zero, returnSpeed * Time.deltaTime);
        currentRot = Vector3.Slerp(currentRot, targetRot, snappiness * Time.fixedDeltaTime);
        transform.localRotation = Quaternion.Euler(currentRot);
    }

    public void RecoilFire()
    {
        targetRot += new Vector3(recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ,recoilZ));
    }```
#

Ive tried checkin every tutorial I can find, but to no avail unfortuneately

#

(how it currently looks)

valid finch
#
void Update()
{
    if (football.SetActive(false))
    {
        {
            FootballFollow();
        }
    }
}

what is the proper way to do what i'm trying to do here

teal vale
#

Hey. I'm stumped. No issues in my code or anything. I'm trying to make a pickup system and I need to be able to add '1' to an int. Unfortunately, [Int name here] + [number here] doesn't work. does anyone know how to fix this? here's the code: ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class PartPickup : MonoBehaviour
{
public int partsCollected = 0;
public int partsNeeded = 3;

public TextMeshProUGUI progressText;

// Start is called before the first frame update
void Start()
{
    this.gameObject.SetActive(true);
    partsCollected = 0;
    partsNeeded = 3;
    progressText.GetComponent<TextMeshProUGUI>();
}

// Update is called once per frame
void Update()
{
    transform.Rotate(5, 5, 5);

}

public void OnTriggerEnter(Collider other)
{
    partsCollected + 1;

    progressText.text = partsCollected + " out of 3 parts collected";

    Debug.Log("player collision has been detected.");

    this.gameObject.SetActive(false);
}

public void ChangeTextToNextObjective()
{
    if (partsCollected == partsNeeded)
    {
        progressText.text = "Return to Traf's cone.";
    }
}

}

languid spire
#

if (!footbal.isActiveSelf) @valid finch

valid finch
#

thanks

eternal falconBOT
#
💡 IDE Configuration

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

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

VS Code*
JetBrains Rider
Other/None

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

nocturne parcel
rich adder
#

you should configure ur IDE first

nocturne parcel
#

I have no idea how your VS isn't warning you about this

rich adder
#

there is a big syntax error

rich adder
#

alr well you don't because it would be underlining the clear syntax error

nocturne parcel
#

It's because it is a syntax error that should have a big warning

#

So something with your IDE is wrong

teal vale
teal vale
#

fixed now. thanks

rich adder
#

+= to add

#

but yeas for doing +1 you only need ++

teal vale
#

Perfect. TYSM

valid finch
valid finch
#

Thank you both

rare basin
#

I think unity is trolling me hard. Why I cannot add this script as a component to my object? No errors in the console

languid spire
#

you have duplicate class/script names

rare basin
#

no i dont

languid spire
#

whicj will give an error in the console

rare basin
rich adder
polar acorn
rich adder
#

this happens to me sometimes on2022

rare basin
#

I already have the script

#

I cannot add it

rich adder
#

unity needs to recompile

#

something got hinged

ashen ferry
#

https://hatebin.com/lwefatiwcd is this correct way to stop coroutine if its running looks like it doesnt restart if I run another just before first one finishes but ive got a bunch more stuff so idk

rich adder
#

common bug on 2022 afaik

languid spire
#

@rare basin notice how it says duplicate class, so you got the class in a script not called the same

rare basin
#

i restarted unity didin't help i can try to delete Library folder

rich adder
#

not reimport all

rare basin
#

alr let me try

polar acorn
rare basin
#

ok lol

#

thank you @rich adder

rich adder
#

btw it usually happens on Prefabs

#

not sure wtf wrong with 2022

rare basin
#

im having so much issues with 2022

languid spire
rich adder
#

true dat

#

its a buggy mess compared to 2021

teal vale
#

Oops. One more issue. I have 3 seperate GameObjects being picked up. Each separate from eachother in the hierarchy. Do I need to add them onto a parent with a manager script? They all have their own version of the script with the same values set. It feels hard to explain.

languid spire
#

which is a buggy mess compared to 2020
which is a buggy mess compared to 2019
need I go on?

rich adder
#

lol unity 5 ftw

languid spire
#

2017, best yet

teal vale
#

just trying to find out what the heck I'm supposed to take a picture of

rich adder
#

like with code

nocturne parcel
#

Yeah, I was going to ask that. What the problem you're having?

teal vale
# rich adder what are you trying to do ?

I'm trying to change a text UI depending on the current value of an int. Unfortunately due to the fact that there are 3 seperate gameobjects with the same script, every time I pick one up, it just deletes the value and replaces it with 1

#

which was the same value to begin with

rich adder
#

have the smaller pickup script only let that main script add +1 to a count

teal vale
#

so, I do need a parent manager!

rich adder
#

when you pick up, the script on pickup should ideally have reference to that statstracker, or you can make it a singleton, have a static instance of it to easy access

teal vale
#

ok... I am highly unfamilliar with singletons

#

I'll try my best and I'll check back in a sec

rich adder
#

they're pretty easy

#

and powerful

#

just dont use it on everything ofc

teal vale
#

alr. thanks

fair steeple
#

Evening, I'm having a problem with animation events, I have this function in my player animation script:

    public void PlayHit()
    {
        print("yay");
        GameManager.instance.GetAudioManager().PlayHit();
    }

but it is not in the dropdown menu, instead there are a bunch of functions I don't care about.

rich adder
fair steeple
#

Yeah

#

Oh nevermind, I got it working somehow

valid finch
#
if (Input.GetKeyDown(KeyCode.Space) && thisAnim.("hasBallAnim", true))
rich adder
#

GetBool

#

prob

#

what are you trying to do

valid finch
#

Trying to do an action if this animation is true and the player is hitting space

#

but no othere time

rare basin
#

Wdym animation is true

rare basin
#

Parameter on your animator?

valid finch
#
public void Act()
{
    if (Input.GetKeyDown(KeyCode.Space) && thisAnim.GetBool("hasBallAnim", true))
    {
        footballController.Pass();
        thisAnim.SetBool("hasBallAnim", false);
    }

}
valid finch
#

Not understanding

rich adder
# valid finch Not understanding

if you want to check the Animator parameter, use the link.
if you want to check for specific animation/state
Animator.GetCurrentAnimatorStateInfo(0).IsName("AnimationName")

valid finch
#

damn..

nocturne parcel
#

If GetTile() always return a TileBase, how may I check if the returned tile is of a different type?
For example, I have two custom tile classes: LandTile and WaterTile. How may I check if the tile return is water?

#

Won't using returnedTile is WaterTile always return false, as returnedTile will be TileBase?

nocturne parcel
rich adder
#

you do checks

valid finch
#
if (Input.GetKeyDown(KeyCode.Space) && thisAnim.GetBool("hasBallAnim", true))

can you write that with proper syntax.. I am not getting it..

valid finch
#

been looking at the coding hints

rich adder
#

I sent you the link

#

it has the example of use

#

you only need the parameter name

nocturne parcel
#

But nvm I think I figured it out

#

Through the magic of polymorphism, is can still do the check

valid finch
rich adder
valid finch
#

Yeah logic was wrong. Now I gotta step through the code to see where the logic is going wrong. I got rid of the ! there are other logical issues though.

#

thank you again

rich adder
valid finch
#

Oh.. something is just not right. I have to double tap the space bar to get it to happen. So apparently something is set to true or false when it shouldn't be. I'll find it. Could also be the WaitForSeconds. I'd share my code with you if you want to see. I don't need you to fix any of it.. just curious on your thoughts as to how poorly set up it is.

nocturne parcel
#
    public override void RefreshTile(Vector3Int position, ITilemap tilemap)
    {
        for (int x = -1; x <= 1; x++)
        {
            for (int y = -1; y <= 1; y++)
            {
                Vector3Int neighbourPos = new Vector3Int(position.x + x, position.y + y, 0);

                RefreshTile(neighbourPos, tilemap);
            }
        }
    }

Why is my refresh override causing an infinite loop? Been waiting for Unity to enter play mode for like 6 minutes now lol

wintry quarry
nocturne parcel
#

Oh damn

wintry quarry
#

you're calling RefreshTile inside itself unconditionally

#

but it shouldn't freeze Unity

nocturne parcel
#

No, it isn't freezing

#

It's on "hold up" for 10 minutes lmao

wintry quarry
#

that's frozen

nocturne parcel
#

The bar loading the script

#

"Entering Play Mode..."

wintry quarry
#

yeah that's frozen

#

on the first frame of the game

#

This is clearly bad but I suspect you probably also have another infinite loop elsewhere

polar acorn
nocturne parcel
#

Anyways, I adapted from the scriptable tile example tho, I just didn't use a HasRoadTile check cuz I wanted all neighbours to refresh

wintry quarry
#

not to mention that when you check your neighbor, it will then check you, and vice versa

#

also forever

nocturne parcel
#

Any ideas to limit it?

wintry quarry
#

recursion always needs a base case

#

You need two things:

  • keep track of which tiles you checked already and skipped them
  • make some kind of "maximum depth"
nocturne parcel
polar acorn
wintry quarry
#

it's calling tilemap.RefreshTile

nocturne parcel
#

AAAAAh

#

Lmao

polar acorn
#

Actually, yeah that's a different refresh tile

nocturne parcel
#

I didn't realized I was not calling the tilemap

wintry quarry
#

although I guess that might be ultimately calling this function

nocturne parcel
#

I shouldn't be using recursion at all then

#

I'm sorry

wintry quarry
#

the other thing is that they are checking a condition: if (HasRoadTile(tilemap, position))

nocturne parcel
#

Yeah, but that is only to refresh the same tiles

#

I'll test with the tilemap refresh, see if it causes the same behaviour

#

Nope, with tilemap refresh

#

all is fine

tender stag
#

why when i pickup the items in a small window, then enlarge and drop they are like twice the size?

nocturne parcel
#

Could swear I read the example as using recursion. Sorry for wasting your time.

tender stag
#

but then when i pick them up and drop in the same size game window

#

it works properly

wintry quarry
tender stag
#

yeah let me show u the drop code

#
public void Drop(Item item)
{
    audioSource.PlayOneShot(item.itemData.dropClip);

    item.transform.position = dropPosition.position;
    
    item.GetComponent<Rigidbody>().AddForce(dropPosition.forward * 5f, ForceMode.Impulse);
    item.GetComponent<Rigidbody>().AddForce(dropPosition.up * 2f, ForceMode.Impulse);

    item.StartCoroutine(item.StartCooldown());
}```
#

im just setting the position

wintry quarry
#

where do the objects go when you pick them up

#

show the code that calls this code

#

and/or the full script

tender stag
#

my inventory manager pickup

nocturne parcel
#

Yo what is that IDE, looks sick

tender stag
#

Item is this

using System.Collections;
using UnityEngine;

public class Item : MonoBehaviour, IInteract
{
    [Header("Item")]
    public ItemData itemData;
    public int amount = 1;

    [HideInInspector] public bool isReady = true;

    public string interactText { get; set; }

    private void Awake() 
    {
        itemData.isDiscovered = false;
    }

    private void Update() 
    {
        HandleText();
    }

    public void HandleText()
    {
        interactText = $"[F] Pick up x{amount} {itemData.name}";
    } 

    public void Interact()
    {
        InventoryManager.Instance.Pickup(this);
    }
    
    public IEnumerator StartCooldown()
    {
        isReady = false;
        yield return new WaitForSeconds(1f);
        isReady = true;
    }
}```
wintry quarry
#

Rider I think?

tender stag
#

item sits on the actual game object

tender stag
queen adder
tender stag
#

i parent the items to the cells

#

slots*

wintry quarry
# tender stag

this doesn't ake sense to me. You're just setting its velocity to 0? How is it disappearing?

wintry quarry
tender stag
#

the slots are canvas images

wintry quarry
#

you're parenting them to UI elements?

#

yeah

tender stag
#

yeaaaah

wintry quarry
#

those will scale differently obviously on different resolution

tender stag
#

bruh

#

this is my cell add method

wintry quarry
#

and restore it when you drop it

tender stag
#

or should i just not parent the object to the cell?

#

im hiding it anyway

wintry quarry
#

just call OnDrop on it when you drop it

wintry quarry
tender stag
#

yeah

#

i'll do that

#

i was parenting it to just keep my hierarchy clean

#

it doesnt really matter too much

wintry quarry
#

Which function exactly do you want to take a string parameter?

#

and where is the string going to come from?

#

and is ButtonTable[0] the GameObject you want to pass in?

analog depot
#

hi there - thinking about a second map for our game, is the pro best practice to just duplicate the entire game config as another scene and setup the new scene? seems difficult, i want all the same managers/players/inputs etc just on a different map

analog depot
#

is there a cleverer way to load a new scene/map/bit of scene that allows me to change the 'level' without rebuilding all the gameobjects/script mappnig etc

wintry quarry
#

use additive scene loading

#

duplicate nothing

analog depot
#

yea we have prefabs for some things, defo could do more, you mean setup prefabs with all the right scripts etc?

wintry quarry
#

Well I wouldn't set up a prefab with the wrong scripts

analog depot
#

additive scene loading - I think i've read that somewhere

#

@wintry quarry all my scripts are the wrong ones 🙂

#

is that where unity partially loads another scene into the current one?

#

i'll google it

analog depot
#

ace - thanks for the pointer

wintry quarry
#

for example if you have a bunch of baseline objects you need in every scene you can load that bootstrap scene first then additively load the actual game levels

analog depot
#

yea makes sense, I think i saw it used for big sprawling partial load maps but makes sense for smaller setups, load the new parital and boot the player and camera over there

tender stag
#

also one more thing, when i just drop an item, and pick it up the text disepears, but when i split the item, and i pick it up, the raycast in my interaction script isnt detecting that it got picked up

#

this is my split script

#

i have no idea what is happening

rich adder
#

!code

eternal falconBOT
#
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.

rich adder
#

oh my b didnt read ur msg

#

just got blinded by ur screenshot

tender stag
#

maybe something with instantiating the item when im splitting?

rich adder
tender stag
#

this is the better way

valid finch
rich adder
rich adder
valid finch
#

Something in the logic is f**ky.. I have to hit spacebar twice to have the ball drop off the player.

rich adder
tender stag
#

OH

#

wait what

rich adder
graceful spruce
#

hey, @rich adder i tried the coroutine but cant seem to find whats the mistake in my code. I want it so when the enemy hits a tower it reduces the health of tower. but I want the enemy to attack like every 1 or 2 second. I made a oncollisionstay2D but it instantly killed the tower,

rich adder
#

did you intend to write .lossyScale btw

tender stag
#

where?

rich adder
#

oh wait thats a thing

rich adder
tender stag
#

i got rid of that

valid finch
#

I'll be back in like 15 minutes or so if you get a chance to look at that send me a reply. Thanks dude

tender stag
#

i didnt need it anymore

rich adder
#

you need code inside

graceful spruce
#

oh

#

but can i add a private void inside a enumerator?

rich adder
#

btw that isnt OnCollisionStay2D

#

its collisionenter

rich adder
graceful spruce
#

o

rich adder
#

you can use onTriggerstay2d if you want an area of damage ? or do you want only edges

graceful spruce
graceful spruce
rich adder
#

hmm in that case you should only call coroutine if 1 is not running already

graceful spruce
#

so what do i do now?

rich adder
#

put damage method after the waited seconds

graceful spruce
#

alright

#

wait

#

do i add the void oncollisionstay?

#

below the wait for seconds

#

i made the bool

rich adder
# graceful spruce alright

eg

 private void OnCollisionStay2D(Collision2D col)
    {
// put same towercheck here 
        if (attacking) return;
        StartCoroutine(Attack());
    }

    bool attacking;
    IEnumerator AttackTime()
    {
        attacking = true;
        yield return new WaitForSeconds(time);
        //Attack()
        attacking = false;
    }```
graceful spruce
rich adder
#

something like that sure, put the attack in there

#

check if its not null

ashen ferry
#

yo what theme is that

rich adder
#

grape ape

#

xD

valid finch
#

Looks awesome

graceful spruce
#

its called

#

the theme is called

rich adder
#

🥁

graceful spruce
#

Minimal wave - dark floral

ashen ferry
#

its for VSC sadok

rich adder
#

lol was trying to replciate it but failed

#

i need to find out the exact hex color

rich adder
graceful spruce
ashen ferry
#

oh u fr ill look it up ty

graceful spruce
#

cryga still doesnt work navarone

rich adder
graceful spruce
#
{
    public int damage = 5;
    
    private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.gameObject.GetComponent<TowerHealth>())
        {   
            collision.gameObject.GetComponent<TowerHealth>().health -= damage;
            if (attacking) return;
            StartCoroutine(AttackTime());
        }
    }
    public bool attacking;
    IEnumerator AttackTime()
    {
        attacking = true;
        yield return new WaitForSeconds(2f);
        attacking = false;
    }
}```
rich adder
graceful spruce
#

the enemy just kills the tower within like 5ms

rich adder
#

your attack goes in the timer

graceful spruce
#

wait fr

#

do i add the if function or no need

rich adder
#

you need to pass it Tower

graceful spruce
#

i dont get it

rich adder
# graceful spruce i dont get it
private void OnCollisionStay2D(Collision2D col)
    {
        if(col.gameObject.TryGetComponent(out TowerHealth towerHealth))
        {
            if (attacking) return;
            StartCoroutine(AttackTimer(towerHealth));
        }
    }
    IEnumerator AttackTimer(TowerHealth towerHealth)
    {
        attacking = true;
        yield return new WaitForSeconds(timer);
        towerHealth.health -= damage;
        attacking = false;
    }```
🥣
graceful spruce
#

OHH

#

alright tysm appreciate it

rich adder
graceful spruce
#

alright noted!

#

👍

valid finch
#

Yeah.. I am having to double tap my spacebar to get the ball to drop. Something is off in the logic. I am sure I will eventually find it. I'm sure it's something simple

rich adder
#

hard to say without context 🤷

valid finch
#

I'm sure I wrote this is a non optimal way..

rich adder
valid finch
#

footballFollow position

rich adder
#

you mean footballFollowing

valid finch
#

The football is being enabled after being disabled

#

yeah

#

wait

#

at the bottom of the footballController code

#

bottom of the page

rich adder
#

Pass?

valid finch
#

Yeah pass (the space bar is supposed to drop it)

#

it does, but I have to tap it twice quickly while footballFollowing is disabled. It reEnables after short time

rich adder
#

is it on a player its probably trigger again no?

valid finch
#

I found the area with the issue I think

#

From the Ienumerator PickedUpFootball down.

And look at the Act() method

#

something in there is wrong..

rich adder
#

maybe its that animator bool ? are you looking at it in the inspector how it acts

valid finch
#

When I press spacebar once the footballFollowing is false.. and it switches back to true automatically

#

but if I hit the spacebar again inbetween when it switches back it drops the ball

rich adder
#

is possible PickedUpFootball coroutine is called twice or something

queen adder
#

will there be any problem if i have this active monobehaviour in builds?

#

this is a monobehaviour (got cropped blushie )

timber tide
#

But you've got it to execute only in the editor

#

probably compiles out when you build

ashen ferry
#

aint UNITY_EDITOR directive is precisely for that lol

wintry quarry
#

Assuming this GameObject exists on any object that isn't tagged as editor only

fair steeple
#

Hey, what is the point of this? Is it so I can access the GM from other classes through GM.instance? Is there any other reason to do this?

timber tide
#

A singleton? Only one instance of the class can exist, so it's doing some checking to not make dupes

wintry quarry
fair steeple
#

Thanks

supple wasp
#

How can I make a tire go flat and have a physical re-flat?

covert matrix
#

Hi reasking about an issue i have since yesterday

im trying to make a gameobject active when pressing the Z key while the player is colliding with an npc.
the player does stop when the player's and npc's collider hits, but nothing shows up on console logs when they do, so pressing Z does nothing

went through the suggestion from @/boxfriend to use https://unity.huh.how/programming/physics-messages but none of the fixes there seems to be my issue

https://gdl.space/ewatuluwet.cs

summer stump
# covert matrix Hi reasking about an issue i have since yesterday im trying to make a gameobjec...

So.. i want to ask the standard troubleshooting questions, but it seems like quite a bit has been gone over already?
So just rapid fire:
1 The CharacterController is on one of the colliding objects?
2 Both objects have colliders, and neither are set to be a Trigger?
3 Both objects have a rigidbody2d?
4 The collision matrix isn't disabled between their layers?
5 Neither of the rigidbodies have layer overrides set to anything but "nothing"?
6 are either of the objects moving really quickly? You ARE teleporting, so this could be an issue

I haven't gone through the unity.huh.how guide for this throughly, but I'm sure all of that is covered there, sorry.

sturdy cove
#

Having trouble getting these two scripts to work for my health pickup item in my game. It keeps giving me a "not set to instance of an object" error

covert matrix
# summer stump So.. i want to ask the standard troubleshooting questions, but it seems like qui...

thanks for the help

  1. the script i provided is attached to the player gameobject
  2. both the npc and player objects have boxcollider2d, neither is set to isTrigger
  3. only the npc has rigidbody2d
  4. both objects are on the interactableLayer, in proj settings there is a check mark between interactableLayer and interactableLayer
  5. i dont think so? all the settings are default except making the npc kinematic
  6. none of the objects are moving
summer stump
sturdy cove
ashen ferry
#

do these events even run on kinematic rigidbody lol

summer stump
ashen ferry
#

ontrigger yea but oncollision no

summer stump
ashen ferry
#

he doesnt have rigidbody on player at all

#

from what he told

summer stump
# ashen ferry he doesnt have rigidbody on player at all

Yeah, I know, I pointed that out. I am confused by the wording in vertx's page though. It says:
"A Collider 2D is required on both objects, and at least one object needs a Rigidbody 2D"

It's worth trying having an rb on both though for sure

eternal needle
summer stump
#

Ah, I wonder if that ONE rigidbody is kinematic. Which would not work.
It maybe needs one, but it HAS to be dynamic?

#

Kinematic only works WITH dynamic, which basically means it doesn't work with kinematic lol. So you're right

ashen ferry
#

I think OnTriggerEnter runs with kinematic+ rigidbody on either object and OnCollisionEnter runs with dynamic rigidbody on either

summer stump
covert matrix
#

so i just change it to dynamic?

hidden citrus
#

Hey, I seem to be getting a stack overflow, but can't figure out why.

When i debug the log, it spams this code 13953 times in one go, though it should only fire once? A separate coroutine is only enabling the collider for this to register ONCE within a window. This already works for weapons, but it's not working for this?

All the previous code is working, but when it hits "iDamage" interface, suddenly it breaks down and stack overflows. It's all debugging on one class too.

    private void OnTriggerEnter(Collider other)  
        {
            if (!other.CompareTag("Player"))
                return;

            Debug.Log("Called OnTriggerEnter!");

            if (other.TryGetComponent(out IDamageable iDamage))
            {
                Debug.Log($"Damaged {other} + {iDamage}");
                iDamage.TakeDamage(1);
            }
        }
#

The target class just has this, nothing special. Hasn't been an issue. Not sure why the interface is going crazy

        public void TakeDamage(int amount)
        {
            TakeDamage(amount);
        }
summer stump
covert matrix
#

all right thanks everyone

#

i’ll have to try that later since i dont have access to my computer atm

ashen ferry
#

in ur TakeDamage method u call it again lol

valid finch
#
 if (!football.activeSelf) //if football is not Active
 {
     Debug.Log("Football Following");
     {
         FootballFollow(); //have football follow player

     }
 }
 else (football.activeSelf)
 {
   
 }

why is this not ok?

sturdy cove
#

The empty object was just there to actually implement the health system beforehand

eternal needle
#

itll help if later on you have the same issue

sturdy cove
#

Will do

#

Thx

eternal needle
valid finch
#

Was giving me an error. I needed to move it anyways. It's bettering within the Football Following method anyways

eternal needle
#

you should post what the error is whenever u have issues like that, the only thing i really noticed is that you have an extra {} for no reason around FootballFollow();

valid finch
#

let me retype this

#

That isn't my final code for the else statement. It is just where I am trying to think of how to do that

eternal needle
valid finch
#

Yes it points to the player

#

so like = new vector3

#

something like that

eternal needle
#

well then it seems like you would just want to do following.transform.position again, but that would mean your if and else do the same thing

valid finch
#

The football game object is disabled. while the player has the ball. Then it is enabled when it is dropped.

#

But the issue is.. if I drop it on my players location it just picks right back up

#

I won't always be this useless.. once I get rolling I won't have as dumb of questions lol

eternal needle
#

this sounds like a completely separate issue tbh, the if statement isnt needed since both if and else are gonna be doing the same thing. If you want to place it at some offset then that would be different like placing it 1 unit infront of the player

valid finch
#

I have that method running in the update

#

so when the ball is enabled the if runs

#

and when it is disabled the else runs

summer stump
valid finch
eternal needle
valid finch
#

following.transform.position(+5,0,0); just trying stuff at this point

#

used it like a method.. which is an error

pseudo frigate
#

i have a smoke particle system as a child of the enemy. when the enemy dies a random force is applied so it falls/rolls in a random direction. im having an issue where the smoke sometimes emits into the ground if the dead enemy rolled a certain way. i was thinking of applying a script to the GO with the particle system on it to keep it rotated in a favorable direction but not sure exactly what to do if someone could help me out? or is there something i could change on the particle system itself to behave the way i want?

eternal needle
valid finch
#

What is the syntax.. new vector3 (following.transform.position x, following.transform.position y, following.transform.position z)

timber tide
valid finch
eternal needle
valid finch
#
Vector3 stopFollow = new Vector3(following.transform.position.x + 5, following.transform.position.y, following.transform.position.z);
football.transform.position = stopFollow;
ivory bobcat
#

You could refactor with cs var stopFollow = following.transform.position; stopFollow.x += 5; football.transform.position = stopFollow;

#

Every call to Transform dot Position property returns a new Vector3.

valid finch
#

Thank you , just looked uprefactoring.

#

I am about at the point of just scrapping what I have and starting over. I feel like my code should be more optimized.. and I feel like I have too much shit for what needs to be done. It should be wayyy way less steps than this

#

Want to see my code and tell me how much of a mess it is? Constructive critisism is welcome. I can learn from it

ivory bobcat
#

Premature optimization is unnecessary but refactoring of code could reduce length, create reusable patterns, and be more readable. Reduction in length is the lesser important of these.

#

I'm on mobile and won't be able to write code

valid finch
#

Do you mind if I explain what I am trying to accomplish. It shouldn't be this involved for what simple stuff I am trying to do

#

Oh I don't mind. Don't need you to. Just curious of your thoughts

ivory bobcat
solid coral
#

How correct is it to write code like this? Maybe you should make a nested condition?

round scaffold
#
    public int _splatterCount;

    private void Update() {
        for (int i = 0; i < _splatterCount; i++) {
            CreateBloodSplatter();
        }
        if(Input.GetKeyDown(KeyCode.R)) {
            var random = Random.Range(1, 5);
            _splatterCount += random;
        }
    }
    public void CreateBloodSplatter() {
        var splatter = Instantiate(_bloodSplatter);
        splatter.transform.parent = transform;


    }```
#

im trying to make a code that creates an object on the screen for every _splattercount there is

#

but this makes the loop go on infinitely

gaunt ice
#

the loop is fine but you create objects in every update loop

compact peak
#

When you put code in update it'll run every frame
You could fix this by using a boolean value, createdBloodSplatter, and only run that loop if that value is false. Once the loop is complete set it to true.

round scaffold
#

okely dokely

#

thank u blonde girl and sentient glass of juice

valid finch
#

My god... I just spent 2 freaking hours.. wondering why my code wasn't working... and it turns out I had something like this

if (blah blah blah {}
{
the code..
}

I cannot believe that

covert matrix
lethal cargo
#

assets for fps game pls

fringe pollen
lethal cargo
#

yea

fringe pollen
#

No I mean go to Unity asset store

lethal cargo
#

alr

#

but none work

verbal dome
#

Less nesting feels cleaner to me

wicked pulsar
grave jay
#

If i want to store a single value (for example, a string or specific script) in a gameobject should i use the variables component?

verbal dome
grave jay
#

talking about this one

verbal dome
#

You can make a MonoBehaviour script and store your variables there

verbal dome
grave jay
#

im trying it out, im asking to know if its more efficient to use this or to just make a new script to store the variables

verbal dome
#

No idea if visual scripting lets you access variables from a regular script

#

This channel is for C#. Which is more efficient that VS

#

And no, we dont use the variables component with C#, we put variables into script components instead

grave jay
#

alright

tender stag
#

can some help me?

#

when i interact the method ResetInteraction() gets called

#

the problem is that when i interact with something, in this instance im picking up an item

#

in HandleInput() i interact when i press f

#

and it debugs that its interacted

#

then it resets the interaction

#

but then then the raycast somehow still sets it again

#

which causes the text to now dissepear because the timer gets set again

#

its only when i split items

#

wait no its only when im stacking items

#

so its prob the order of execution

#

when i interact with my item the interact gets called

#

which then calls the pickup method

#

which calls the add method

#

which then calls the add method in the cell

#

thats when the item is not hitable by the raycast anymore because im setting it to now active

#

but when im stacking items it somehow runs faster?

fickle karma
#

YO.
So my onclick function is not finding my changebuttoncolor function which i made. How do i fix this? 🙂

north kiln
tender stag
#

when i was adding to an existing stack

#

i was just destroying the item game object

#

because i was just adding the amount since i was adding to stack

#

but i just added item.gameObject.SetActive(false);

#

before i destory it

#

and the raycast doesnt detect it anymore

#

which is what i want

#

why?

#

if im destroying it, its not gonna be there anyways, so the raycast shouldnt set it again

#

or maybe the Destory gets called a second later than SetActive does?

#

In Unity, when you destroy an object using Destroy, it's not immediately removed from the scene. Instead, Unity marks it for destruction, and it will be removed during the next frame or at a later point when Unity's garbage collection system processes it. This means that the object still exists in the scene (albeit as a "to be destroyed" object) until it's actually removed.

#

thats why

#

alright

#

brainstorming sometimes helps

celest shoal
#

IDK if this is the right area to post - sorry. I have a large pixel art sprite, however using point and zero compression, the quality is a bit blurry. I have a solution for importing the sprite as sections but I want to know whether there is a way for it to be done on unity instead

oblique gazelle
#

hello

#

I need help

#

pls

#

my raycast does not hit the target

#

someone know how to solve it?

celest shoal
#

Thanks

oblique gazelle
#

could someone help me with weapon and animation shoot?

weak talon
#

I am making 2D top down movement

code:
float vInput = Input.GetAxis("Vertical");
float hInput = Input.GetAxis("Horizontal");

    transform.Translate(Vector3.up * moveSpeed * vInput * Time.deltaTime);
    transform.Translate(Vector3.right * moveSpeed * hInput * Time.deltaTime);

the only problem is when i move diagonally it moves faster
does anyone have a fix for this

slender nymph
#

you'll want to create a Vector3 from your input and normalize that (or clamp its magnitude to 1 if you want to support moving slower for analog inputs that are not fully activated)

weak talon
slender nymph
#

do you know how to create a new Vector3?

weak talon
#

yeah

slender nymph
#

so do that and use the vInput as the Z axis and hInput as the X axis

#

then you can use that Vector3 .normalized instead of Vector3.up * vInput and Vector3.right * hInput

weak talon
#

got it thanks

sullen rock
#

FPS isnt whats supposed to be falling kekwait

#

okay, I see now, debug.log took away my 150 FPS

slender nymph
#

is there a particular reason you're waiting for the end of the frame instead of just yield return null to wait for the next frame?

verbal dome
vocal marlin
#

So I'm making a roguelike where you can choose a splitting path of rewards every time you beat a level however the rewards require you to go into a different scene and when you go back, the rewards are different, which I don't want to happen. Is there anyway I can recreate the rewards path to be the exact same as it was before. Here are the important parts of the script. I can post it all in a paste bin if you want to see it all.

public void CreateSplitPath()
    {
        Debug.Log("path creating");
        for(int i = 0; i < numberOfPaths; i++)
        {
            GameObject gamePath = Instantiate(path, Vector3.zero, Quaternion.identity);
            gamePath.transform.SetParent(pathArea.transform, true);
            gamePath.transform.localScale = Vector3.one;
            //gamePath.transform.localPosition = new Vector3(100 * (i + 1), -85, 0);
            for(int j = 0; j < nodesInPath; j ++)
            {
                GameObject pathNode = Instantiate(pathNodeButton, Vector2.zero, Quaternion.identity);
                string pathType = possibleScenes[Random.Range(0, possibleScenes.Count - 1)];
                pathNode.GetComponent<GamePath>().sceneToLoad = pathType;
                pathNode.GetComponent<GamePath>().path = i + 1;
                pathNode.GetComponent<GamePath>().pathNumber = j + 1;
                pathNode.transform.SetParent(gamePath.transform);
                pathNode.transform.SetSiblingIndex(0);
                pathNode.transform.localScale = Vector3.one;
                pathNode.GetComponent<Button>().onClick.AddListener(delegate{OnNodeClicked(pathNode.GetComponent<GamePath>());});
                pathNode.GetComponent<GamePath>().levelSelection = this;
                pathNode.GetComponentInChildren<TextMeshProUGUI>().text = pathNode.GetComponent<GamePath>().sceneToLoad;
            }
            
        }
        //Spacing();
    }
#
public void Start()
    {
        level.CalculateStartingCards();
        cardNumberText.text = "Number of Cards: " + level.startingCards.ToString();
        turnsAllowedText.text = "Number of Turns: " + level.turnsAllowed.ToString();
        nextLevelButton = GetComponent<NextLevelButton>();
        nextLevelButton.nextLevelButton = GetComponent<Button>();
        nextLevelButton.pathsUntilNextLevel = numberOfPaths + 1;
        nextLevelButton.levelSelection = this;
        if(pathNumber == 1)
        {
            CreateSplitPath();
        }
        else
        {

        }
        DataPersistenceManager.instance.SaveRun();
    }
verbal dome
vocal marlin
#

sorry, i read the docs and am struggling to figure out how to use this for my game.

#

i know its probs really simple but ima bit dumb

slender nymph
#

i see you call DataPersistenceManager.instance.SaveRun(); presumably to save the data that you need, right? so where do you load that data?

vocal marlin
#

its loaded onsceneloaded in a datapersistencemanager script

slender nymph
#

okay so where do you access that data in this script to use it instead of overwriting it with new data?

#

or is that somehow completely unrelated to what you are trying to do?

vocal marlin
#

i tried doing this but it doesnt seem to work

public void LoadData(RunData data)
    {
        currentPath = data.currentPath;
        pathNumber = data.pathNumber;
        pathArea = data.currentPathArea;
    }

the path area is the place where the paths are and it should hold all the paths from before but it's just blank

slender nymph
#

then you need to look at what you are saving and how to make sure you are actually saving the data that you need

vocal marlin
#

i think i see the problem, i just saved the game object to the data file, which wouldnt be the same as the one in the scene so it just wouldnt be able to create a path

#

however i dont know what other method i could use to save it to a file and reload it, do you have any method?

slender nymph
#

save the relevant data stored on the components, not the actual components themselves

vocal marlin
#

ok ill try this ty

rare basin
#

if i a have a structure in the hierarchy like this:

  • A
    • B
      and the B object has script with OnEnable and OnDisable functions, but im only disabling object A will it also work?
#

if not, how can i do that?

sullen rock
#

well thats new to me

slender nymph
#

yes

#

and it doesn't allocate garbage either

sullen rock
#

is there any difference?

#

okay thats double new to me

#

thanks

#

I assumed yield return null just.... doesnt wait, lol

#

so I didnt even consider looking up anything about it

slender nymph
#

WaitForEndOfFrame doesn't wait for the next frame, it waits for the end of the current frame, it just happens that the next time it is encountered it will be waiting for the end of the next frame. and every time you do new WaitForEndOfFrame() you're creating more garbage

sullen rock
#

so yeah, the reason is, I had no idea

#

and its good that I do now because I use this in every damn project

slender nymph
#

another thing about WaitForEndOfFrame, since you undoubtedly started the coroutine sometime during the frame before that condition would be met, it actually runs 2 loops in the first frame

sullen rock
#

that makes no sense to me

#

like, if I start in in the middle of a frame, it will just wait the half of the frame thats left, no?

slender nymph
#

https://docs.unity3d.com/Manual/ExecutionOrder.html
say you start your coroutine in Update. it runs until it hits the first yield. so it basically completes everything but the yield in loop. then at the end of the frame, the yield has completed so it runs again until it hits the next yield. then the frame progresses. so now you've completed the loop two times

sullen rock
#

ohhhh

#

I get it

#

thanks

slender nymph
#

@rare basin i don't know why you are reacting with the "it depends" react on that. that is how that works

#

or are you just salty that i suggested you try what you were asking about?

rare basin
#

no, idc

sullen rock
#

well @slender nymph I think this single bit of advice will have the biggest impact on me down the line lol, not that it would be that crucial or something, but its something I wouldnt have even thought about, at least to me, the naming "null" just isnt very intuitive in this case

slender nymph
#

you're just returning null for each yield. so there's no condition for the yield to check so it just continues execution the next time the coroutine is updated (which happens every frame)

#

they probably set it up this way to avoid a lot of garbage creation because YieldInstruction (the base class for each of the types you can yield for a coroutine) obviously creates garbage when instantiated just like any other class

#

that's probably a poor explanation but i hope you catch my meaning

sullen rock
#

I do

#

the source of my confusion was misunderstanding of the yield itself

vocal marlin
sullen rock
#

I´ll read up on it a bit more and Ill be fine

slender nymph
sullen rock
#

thats the issue of not having formal CS education, I sort of know how to use the tools but I dont know how they work under the hood, thus I miss stuff like this

vocal marlin
#

i added this change

string pathType = possibleScenes[Random.Range(0, possibleScenes.Count - 1)];
pathScene.Add(pathType); // null  reference error on this line

apparently that causes a null reference error?
also its spawning some of the path nodes in the wrong place even though i have a line fo code that sets the parent to the right thing, which is just really frustrating and makes no sense.

slender nymph
#

where do you initialize your pathScene list

vocal marlin
#

what do you mean

rare basin
slender nymph
# vocal marlin what do you mean

i mean that if that list is not serialized (by either making it a public field or marking it with SerializeField) then no instance of the list will be created so it remains null

rare basin
#

if you want, you can set the localPos of the snapped object to 0

vocal marlin
stoic spear
#

hey, pretty simple question but my player movement right now is transforming along the global axes, how do i make it local to the players look position? so i move forward in the way im looking

slender nymph
#

transform.TransformDirection

vocal marlin
stoic spear
#

right now i’m just doing rb.AddForce(tgtMoveDir * addspeed, forcemode.force)

slender nymph
#

in that case you can just use AddRelativeForce

stoic spear
#

oh, simple

slender nymph
#

otherwise you would use the TransformDirection method i suggested before to convert the direction to be relative to the object's rotation

orchid trout
#
  private void InitializeMesh()
    {
        meshFilter = GetComponent<MeshFilter>();
        if (ringMesh != null)
        {
            DestroyImmediate(ringMesh);
        }
        ringMesh = new Mesh { name = "Arc" };
        meshFilter.mesh = ringMesh; // this line right here, officer.
    } ```
I need to make changes to a mesh through code in editor, however my console gets spammed with 'Don't do that in OnValidate' 
What is the correct sollution for this - either to suppress the warning or what can I change to no longer proc the warning?

Don't tell me the obvious answer of 'Well just don't do that in OnValidate.' I need to update the mesh when inspector values change, in editor.
#

Well, you can tell me not to do it in OnValidate, if you also tell me where I should do it that will still function in editor UnityChanThink

modest dust
#

Here's a way to suppress it

#

Scroll down a bit

#

Had a similar issue and it worked fine

orchid trout
#
    private void OnValidate()
    {
        EditorApplication.delayCall += DelayedInitialization;
    }

    private void DelayedInitialization()
    {
        InitializeMesh();
        CreateRing();
        UpdateAnchoredObjects();
    }```
delayCall worked great, thanks! 👍
hidden citrus
vestal valve
languid spire
#

Prefabs cannot contain scene objects

cosmic dagger
vestal valve
#

what is the solution then?

wintry quarry
vestal valve
wintry quarry
#

Usually you'd have the script that instantiates the prefab pass the reference to the newly created object

solar tide
#

Some weird ass problems. The formula at the bottom works perfectly, but the codes above isn't being read at all, the "executing to turning to 0" debug log doesn't even appear

wintry quarry
#

You're treating a quaternion as if it's a set of euler angles

#

rotation.y will never be greater than 1

#

And you shouldn't be touching it tbh. Never mess with individual quaternion components if you can help it, which you can

#

Much better to do something like cs if (Vector3.Angle(transform.forward, Vector3.forward) < 1)

solar tide
#

okay, I'll try changing it

wintry quarry
#

Also get in the habit of using else when appropriate instead of duplicating your if conditions

#

You probably even have a bug here where you'll fall into the second condition as a result of the code in the first

oblique gazelle
#

anyone could hewlp me ?

languid spire
#

oh, yeah, and never check floats for equality

oblique gazelle
#

need help to attatck player with knife

stoic spear
#

hey, so whenever i jump, this script seems to zoom me in a random direction at super high speeds and im not sure why :c

    void Update()
    {
        //Camera
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivity, 0);
        cam.Rotate(-Input.GetAxis("Mouse Y") * sensitivity, 0, 0);

        //Movement
        float multiplier = 1;
        if (!isGrounded) multiplier = 0.5f;

        rbLateralVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
        Vector3 tgtMoveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
        
        if (tgtMoveDir == Vector3.zero) rb.AddForce(-rbLateralVelocity * removeSpeed * multiplier, ForceMode.Force);
        else rb.AddRelativeForce(tgtMoveDir * addSpeed * multiplier, ForceMode.Force);
        if (rbLateralVelocity.magnitude > tgtSpeed) rb.AddRelativeForce(-tgtMoveDir * (rbLateralVelocity.magnitude - tgtSpeed + addSpeed * multiplier), ForceMode.Force);

        //Jumping
        Vector3 v3 = new(transform.position.x, transform.position.y+1, transform.position.z);
        if (Physics.Raycast(v3, Vector3.down, out RaycastHit hit, 1.1f)) isGrounded = true;
        else isGrounded = false;
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded) rb.AddRelativeForce(Vector3.up * jumpHeight, ForceMode.Impulse);
    }```
fossil drum
wintry quarry
graceful spruce
#

Hello, I have a code that destroys a gameobject when it touches enemy. In the code I added a [SerializeField] so i can access variable from another script. but when i added more enemies instead of just one. The enemy destroys the game object and destroys the script I added to the [SerializeField] is there anyway to prevent that from happening

wintry quarry
#

And keep the instances in a List if you need to access them.

graceful spruce
#

oh I made a prefab but I think i placed the thing from scene reference