#💻┃code-beginner

1 messages · Page 343 of 1

patent compass
#

Hello. I want to get the current time on my system. Is there any function which can get that?

burnt vapor
#

There's also TimeOnly that is for just the time

#

Pretty sure that is not supported by Unity, though

swift crag
#

also consider DateTime

patent compass
languid spire
burnt vapor
#

Confused it with Javascript

gilded steppe
#

I am trying to get rotation value in the x axis of a game object

#
public Transform target;
var angle = target.localEulerAngles.x;
Debug.Log(angle) ```
#

When I am changing targets value in inspector to something like 50,60,90 it's working properly
But when I am changing it above 90
For example 92
Output is 88 and it keeps decreasing when I increase more than 90

#

How can I solve this issue?

swift crag
#

Euler angles are not unique.

#

There are several ways to represesnt the same rotation.

#

What are you trying to actually do?

gilded steppe
#
joint.spring = spring ```
gilded steppe
swift crag
#

You can use Vector3.Angle to measure the angle between two directions

#
Vector3.Angle(transform.forward, Vector3.up);

e.g.

gilded steppe
#

Is there no way to do this with euler angles?

swift crag
#

as you have discovered, no: all rotations are stored as quaternions internally

#

converting back to euler angles can cause weird jumps

gilded steppe
#

Makes sense

gilded steppe
swift crag
#

If you want to measure how far you've rotated from your parent, consider:

#
Vector3.Angle(transform.forward, transform.parent.forward);
polar nova
#

Anyone have an Idea why Health isn't setting itself to maxHealth when I start the game?

swift crag
#

oh, actually

#

something closer to your original design

#
Quaternion.Angle(transform.localRotation, Quaternion.identity);
#

This is how far you've rotated from the default rotation

summer stump
swift crag
languid spire
polar nova
summer stump
gilded steppe
languid spire
#

Then Health will be 10

polar nova
languid spire
summer stump
languid spire
polar nova
languid spire
polar nova
languid spire
#

Do you not know what the Unity Console is?

polar nova
#

ahh sorry

swift crag
polar nova
swift crag
#

consider this cube. if I rotate it around its local X axis by spinning the red handle, all three local eulers change

gilded steppe
#

Yeah

languid spire
gilded steppe
#
using UnityEngine;

public class SetHandSpring : MonoBehaviour
{
    private HingeJoint joint;
    public Transform target;


    void Start()
    {
        joint = gameObject.GetComponent<HingeJoint>();
    }

    void Update()
    {
        JointSpring spring = joint.spring;
        var angle = 0f;

        angle = target.localEulerAngles.x; // Right
        spring.targetPosition = angle;
        joint.spring = spring;

    }
swift crag
#

I mean, physically, in the scene!

gilded steppe
#

When I try to change targets rotation.x value more than 90
The eulervalue.x starts decreasing

gilded steppe
swift crag
#

What is target? Is it like a dial that you rotate to make the hinge joint rotate?

gilded steppe
#

It's a rectangular cube

#

And the local transform is a hand with rigidbody and hingejoint attached

#

Right now what's happening is
When the target rotates, the hand rotates as well
But as soon as the target rotates more than 90° the local hand rotates in the opposite direction

swift crag
#

ah, so you're making a hand follow the thing it's holding

#

Vector3.SignedAngle can give you an angle ranging from -180 to 180. It sounds relevant here.

gilded steppe
swift crag
#

You give it two vectors to compare, as well as a third vector that defines the axis of rotation

#

(the third vector is what gives you the sign)

#

otherwise you can't really decide if a rotation is positive or negative

languid spire
# polar nova

So you DID NOT add a Debug to the Start method like I asked

summer stump
# polar nova

Consider making both variables private in order to prevent them from being affected by something else.

Also, yes, that debug should be in start, and log the actual value of Health, not just words

rotund egret
#

gusy can you help me im a begainer and im making a game i got a video of the issue but i cant sadly send it here

rotund egret
#

fine i removed it

#

not like anyone is ognna try helping me 🙄

languid spire
rotund egret
#

but i cant send the video here

#

it wont allow me

languid spire
#

so explain it in words

rotund egret
#

I tried

#

No one understood

#

ama just go

swift crag
#

ok

mighty basalt
#

Hey, im making a small game as a learning project and i want to make a procedurally generated open world tilemap. my idea is making small sections of tilemaps as prefabs and then instanciate them when the camera gets close to the edge of the current map. but i cannot for the life of me figure out how i save a tilemap as a prefab. is it not possible or am i missing something?

spare mountain
swift crag
spare mountain
#

oh are you trying to save the component as a prefab?

#

prefabs need to be gameobjects iirc

mighty basalt
#

i see my problem, its because of the way my current tilemap is set up. i think i know how to fix it so ill try that first

#

actually no im not sure. i tried taking the "TileMapBase" and making it a prefab but when i then drag that prefab into the game window, it looks like this. it has saved the collider but not the sprites

spare mountain
mighty basalt
#

im not entirely sure what that means. i have this in my hierarchy and i dragged the tilemap base into the prefabs folder, and then dragges that prefab into the scene

spare mountain
mighty basalt
#

wait it works. it was because it wasnt on the grid object

spare mountain
#

lol told you

mighty basalt
#

thanks a lot 🙂

mighty basalt
# spare mountain lol told you

when making an open world like this, is it best to just make a bunch of mountain prefabs and then instantiate them onto a base layer, or should i make both a base and the mountains in the same prefab?

spare mountain
mighty basalt
#

my tilemap is made up of a base layer with ground tiles and then i have tiles to make mountains to add some diversity to the maps. when i then make the mountains they need to be on a seperate layer than the ground tiles are. so should i make prefabs of the mountains on the ground or just make prefabs of the mountains and instantiate them on a base/ground layer?

spare mountain
mighty basalt
#

okay thx

spare mountain
#

np

solar charm
#

hey! sorry for the question but can someone explain to me why this isnt working? the script is attached to a button and when i press on the button its not printing "HELLOOOO"

spare mountain
solar charm
cosmic dagger
solar charm
cosmic dagger
cosmic dagger
solar charm
cosmic dagger
#

use pointer events via code or the event trigger component . . .

solar charm
cosmic dagger
#

OnMouseDown is for actual GameObjects in the scene that you want to click and interact with . . .

solar charm
#

OHHH yeah that makes more sense...

karmic kindle
#

I don't know how best to ask this question, but, I have a coroutine that runs near the beginning of my level with two different variables, as soon as the second coroutine is called, it switches the variable and runs both coroutines with the "second value" - is there a way for me to make sure they both run along side, or do I have to split the code into separate coroutines?

languid spire
karmic kindle
spare mountain
karmic kindle
#

@spare mountain I can't find out how to highlight it in chat so I replaced it with a link that should work?

cosmic dagger
eternal falconBOT
karmic kindle
#
public IEnumerator HighlightPath(int path)
    {
        if(path == 1)
        {
            highlightedPath = PathPoints1;
            highlightedPoints = pathPoints1;
        }
        if(path == 2)
        {
            highlightedPath = PathPoints2;
            highlightedPoints = pathPoints2;
        }
        if(path == 3)
        {
            highlightedPath = PathPoints3;
            highlightedPoints = pathPoints3;
        }
        for (int i = 0; i < highlightedPath.transform.childCount; i++)
        {
            if (i != highlightedPath.transform.childCount - 1)
            {
                int j = i + 1;
                GameObject arrow = Instantiate(arrowObject, highlightedPoints[i].position, Quaternion.identity);

                arrow.transform.LookAt(highlightedPoints[j]);
                Destroy(arrow, 0.75f);
                Debug.Log("I should be highlighting pathpoint > " + highlightedPoints[i] + " & pathpoint >" + highlightedPoints[j]);
            }
            
            yield return new WaitForSeconds(1f);
        }
    }```
spare mountain
#

```cs
test

as such
karmic kindle
#

The code runs for # time, then when it's called with "path == 2", the first call is replaced with the new value

spare mountain
karmic kindle
#

Sorry! The coroutine is called at the very start of the game, then it is eventually called again, but usually the first time the coroutine is called, hasn't finished yet, so instead of carrying on with the first array (PathPoints1), both coroutines are now using the second array (PathPoints2)

cosmic dagger
cosmic dagger
karmic kindle
swift crag
#

If every coroutine should have the same value, just make it a field on the class.

karmic kindle
#

The premise is a tower defense game, I'm showing the path to the player by highlighting the waypoints enemies are walking across. It works okay until I try to show path2 and/or path3 - while HighlightPath(1) is showing and HighlightPath(2) is called, "HighlightPath(1)" (through debug.log) now shows the values according to the new "HighlightPath(2)"

tranquil vault
#

Heya, so I need help with making an infinite runner, I have a parallax background, but the thing is that it's with a fixed camera, and I'm trying to have it so where a group of sprites move and reset their position, I'm not sure how to achieve that.

#

This is what I have now

#

And this is the code I'm working with to try and achieve it

    [SerializeField] bool scrollLeft;

    float singleTextureWidth;

    void Start()
    {
        SetupTexture();
    }

    void SetupTexture()
    {
        Sprite sprite = GetComponent<SpriteRenderer>().sprite;
        singleTextureWidth = sprite.texture.width / sprite.pixelsPerUnit;
    }

    void Scroll()
    {
        float delta = moveSpeed * Time.deltaTime;
        transform.position += new Vector3(delta, 0f, 0f);
    }

    void CheckReset()
    {
        if ((Mathf.Abs(transform.position.x) - singleTextureWidth) > 0)
        {
            transform.position = new Vector3(0.0f, transform.position.y, transform.position.z);
        }
    }

    void Update()
    {
        Scroll();
        CheckReset();
    }
#

Granted, I still need to figure out how to implement it as a group instead of relying on the size of a singular sprite

cosmic dagger
valid roost
#

any idea what this means

queen adder
verbal dome
short hazel
#

Perhaps you meant to do that on the spawnPoints list instead?

languid spire
short hazel
#

They access spawnPoints on 41, so they may want to remove them from the available spawn points for the next iteration

languid spire
#

but the error throws on 42 which is the RemoveAt

#

makes no sense to me either

short hazel
#

Yes they do that on the wrong list presumably

languid spire
#

but the index is generated on numbers and the remove is also numbers

#

I think they changed the script and didn't post the correct version and you are correct it's the Instantiate line throwing the error

queen adder
#

its the latest version

languid spire
#

big doubt

queen adder
#

i checked it is

languid spire
#

then the error is not from that version

short hazel
#

If there's { 1, 3, 6 } in numbers and 6 is randomly picked out, then the RemoveAt(6) will fail because the list doesn't have an element at index 6

languid spire
#

no
int spawnPointIndex = numbers[Random.Range(0, numbers.Count)];

spare mountain
languid spire
#

but this
spawnPoints[spawnPointIndex]
could definitely throw an error

queen adder
#

does the spawnpoint array need to have 6 or it can have less

languid spire
short hazel
#

What is this code supposed to do?

spare mountain
languid spire
short hazel
#

Assign random spawn points to random enemies?

queen adder
#

obstacles but yea basically

#

8 spawn points, 2 different obstacles but want to add more in future

short hazel
#

You should really name your lists so it's explicit on what they are and what they store

queen adder
#

yea my bad on that

short hazel
#

So, once a spawn point is "consumed" it should not be used anymore to spawn obstacles, correct?

#

Hence the removal from the list on L42

#

Made on the wrong list

languid spire
#

this
int spawnPointIndex = numbers[Random.Range(0, numbers.Count)];
Instantiate(obstaclePrefab, spawnPoints[spawnPointIndex].transform.position, Quaternion.identity);
is what worries me, an index based on numbers but used on spawnPoints

queen adder
short hazel
#

There's 7 spaces and it fills out 6 of them for each "obstacle row" if I read the code correctly

languid spire
short hazel
#

Or just numbers.Remove(spawnPointIndex)

languid spire
#

indeed

short hazel
#

That eliminates the spawn point that was just chosen

queen adder
#

thank you so much steve lol

short hazel
#

.Remove(n): removes the first occurrence of n in the list wherever it is
.RemoveAt(n): removes the element at index n whatever it is

queen adder
#

oh

short hazel
#

I think you're mixing up the two

karmic kindle
# cosmic dagger if the highlighted path and points are suppose to be separate, then make them lo...

Just taking the learning opportunity, but is this what you meant? It now does what I expect ```cs
public IEnumerator HighlightPath(int path)
{
if(path == 1)
{
highlightedPath = PathPoints1;
highlightedPoints = pathPoints1;

        yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
    }
    if(path == 2)
    {
        highlightedPath = PathPoints2;
        highlightedPoints = pathPoints2;
        
        yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
    }
    if(path == 3)
    {
        highlightedPath = PathPoints3;
        highlightedPoints = pathPoints3;
        
        yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
    }
}```
short hazel
#

If you're finding yourself using numbered variable names (pathPoints1, pathPoints2), you should be using an array instead

#

This code would be shortened down to:

public IEnumerator HighlightPath(int path)
{
    highlightedPath = PathPoints[path];
    highlightedPoints = pathPoints[path];
    yield return StartCoroutine(HighlightThisPath(highlightedPath, highlightedPoints));
}
languid spire
#

pretty sure the two highlighted... variables should be local not class scope

short hazel
#

Yep that too, unless there's too much spaghetti already and they're used elsewhere

languid spire
#

it's gonna screw up if you have more than one routine running

waxen umbra
#

!vc

eternal falconBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

shadow briar
#

Hi all, so new to newish to unity and im trying to wrap my head round using inheritance.
I get the gist of it but its more so the use of it in other objects.

Did some google searches and im kinda just going in circles following "how to access data from other scripts".

So making a script that has the class and inheriting classes, but now i want to actually use these classes.
So im making entity classes, so for example gonna be using it for animals, Hostile NPC.

public class Entity_Base : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField] protected string EntityName;
[SerializeField] protected string Description;
[SerializeField] protected float movementSpeed;
protected enum Entity_Alert_State
{   Idle,Flee,Patrol,Combat}
[SerializeField] protected Entity_Alert_State AlertState;
 
}

public class Human_Entity : Entity_Base
{
    public readonly int HumanNumber;

 }```
As a quick example, but now actually *using* it im kinda stumped, if anyone can link me to anything or give a brief guide anything would be appreciated.
rich mountain
#
    private void AnimateMoneyGain(int amount)
    {
    Vector3 spawnPosition = new Vector3(100, 500, 100);
    GameObject gainMessage = Instantiate(moneyGainMessagePrefab, spawnPosition, Quaternion.identity, transform);
    
    TextMeshProUGUI gainText = gainMessage.GetComponentInChildren<TextMeshProUGUI>();
    gainText.text = "+$" + amount.ToString();

    Animator gainAnimator = gainMessage.GetComponent<Animator>();
    gainAnimator.SetTrigger("GainMoney");
    Destroy(gainMessage, 2f);
    }

    private void AnimateMoneyLoss(int amount)
    {
    Vector3 spawnPosition = new Vector3(0, -100, 0); 
    GameObject lossMessage = Instantiate(moneyLossMessagePrefab, spawnPosition, Quaternion.identity, transform);
    
    TextMeshProUGUI lossText = lossMessage.GetComponentInChildren<TextMeshProUGUI>();
    lossText.text = "-$" + amount.ToString();

    Animator lossAnimator = lossMessage.GetComponent<Animator>();
    lossAnimator.SetTrigger("LoseMoney");
    Destroy(lossMessage, 2f);
    }

Any idea on why my texts are not spawning in the right spot?

languid spire
#

you have 2 hardcoded spawn positions
Vector3(100, 500, 100);
Vector3(0, -100, 0);
what is wrong with them?

rich mountain
#

They not in the right postion, I tried editing them but they didnt move the text at all either

night mural
night mural
rich mountain
night mural
languid spire
night mural
#

the way a ui element might be if you tried to use it in the world?

rich mountain
shadow briar
# night mural can you attach your human entity script to a gameobject? that said, if you're j...

So Human Entity is in the same script as Entity script.
i was thinking that i can keep all the generalised template in the same script and get references to them or something.

But if its gonna be like Base script, than i create Human script than Dog script i can understand how to use that yeah.

i just was unsure what is the actual method of using inheritance in Unity, since i am more use to Unreal

languid spire
#

then you should be using the RectTransform methods

night mural
#

so if you move your child class into its own file, you'll be able to use it like you are expecting

#

though you might need to move to PascalCase classes, i donno if unity will like your underscores (but maybe it doesn't matter, not sure)

shadow briar
#

hm hm well i can do their own scripts
cheers for the help, i was just assuming i could basically make a template script and use what i want from them.

But cheers for the help

vale karma
#

hello, question about Cloud Save. I have the sign in page initialized on the Login Scene, and have my loading and saving on the actual application scene. It all works perfectly, but i want to display which user is currently logged in, and display that through a TMP_Text. Is there a way to pull a value from a previous scene? or save that value to the future scene?

night mural
shadow briar
night mural
#

maybe it's helpful to understand that 'dragging a component onto a gameobject' is the same as instantiating an instance of that component's class and attaching that to the gameobject

vale karma
#

can scriptable objects temporarily save data between scenes?

night mural
#

they exist outside of any concept of the scene

vale karma
#

sweett i think i can figure this one out 😄 every time i come to type a question ive been able to figure it out before i send it haha

tranquil vault
#

Parallax Help

night mural
#

rubber duck debuggin smart

vale karma
#

I have a toy bird i tell my problems to, it does the same effect lol

#

his name is Scoop, he has icecream and a spin top hat

night mural
#

i wish i had icecream 😦

vale karma
#

it feels so good, i finally coded an entire working app with features i never thought i could build myself. It took so many 2am thoughts haha

feral moss
#
[SerializeField] private Camera camObject;
[SerializeField] private float sensitivity;
void Update()
{
    if (Input.GetKey(KeyCode.A))
    {
        camObject.transform.Translate(sensitivity * -1, 0, 0);
    }
    if (Input.GetKey(KeyCode.W))
    {
        camObject.transform.Translate(0, sensitivity, 0);
    }
    if (Input.GetKey(KeyCode.D))
    {
        camObject.transform.Translate(sensitivity, 0, 0);
    }
    if (Input.GetKey(KeyCode.W))
    {
        camObject.transform.Translate(0, sensitivity * -1, 0);
    }
}

Completely winging it here, I quickly wrote some code for controlling the camera with the AWSD buttons on keyboard
The camera is only moving horizontally, not responding to W or S though. Any idea what's up?

vale karma
#

you probably need to convert the input into actual left right forward view and up view

storm pine
#

How can I do that at the beggining of my scene some Singleton object will be created?
I have this awake on my GameController ```cs
protected override void Awake()
{
base.Awake();
//GameDataController.GetInstance().LoadGame();
gameDataController = GameDataController.GetInstance();
progressBarController = ProgressBarController.GetInstance();
}

And the objects look to be created as shown on the image, but when I try to acces any of their methods or variables it just throws a NullReferenceException as if this object wasn't working. I don't know if it is something from Unity optimization
feral moss
#

Currently I'm just setting the value of sensitivity manually in the scene view

vale karma
#

same, the more i read it the more i get confused XD

strong token
vale karma
#

^^^ yee

feral moss
#

Oh I'm stupid lol

#

Thanks

#

So when I hit W it's moving up and then down the same distance

#

Or rather I guess it’s not moving it all

#

Because those are probably considered simultaneous

rocky canyon
#

it goes one way and then the other..

#

then u see the result at the end of the frame

#

so u perceive it to be simultaneous

strong token
feral moss
#

So it might as well be simultaneous

rocky canyon
#

mmhmm

storm pine
storm pine
mighty basalt
#

what is the easiest way to check if my camera is getting close to the end of my tilemap? should i do something with the cameras position compared to an empty on the edge of the map, or should i do something like "when the player has moved X in this direction, then add new tilemap on this side"?

rich mountain
#
    private void AnimateMoneyGain(int amount)
    {
    GameObject gainMessage = Instantiate(moneyGainMessagePrefab, transform);

    TextMeshProUGUI gainText = gainMessage.GetComponentInChildren<TextMeshProUGUI>();

    RectTransform gainTextRectTransform = gainText.GetComponent<RectTransform>();

    gainTextRectTransform.anchoredPosition = new Vector2(-759, 381); // Adjust this position as needed

    Animator gainAnimator = gainMessage.GetComponent<Animator>();
    gainAnimator.SetTrigger("GainMoney");
    Destroy(gainMessage, 2f);
    }

    private void AnimateMoneyLoss(int amount)
    {
    GameObject lossMessage = Instantiate(moneyLossMessagePrefab, transform);

    TextMeshProUGUI lossText = lossMessage.GetComponentInChildren<TextMeshProUGUI>();

    RectTransform lossTextRectTransform = lossText.GetComponent<RectTransform>();

    lossTextRectTransform.anchoredPosition = new Vector2(-759, 381); // Adjust this position as needed

    Animator lossAnimator = lossMessage.GetComponent<Animator>();
    lossAnimator.SetTrigger("LoseMoney");
    Destroy(lossMessage, 2f);
    }

The text is still not spawning in right position after changing the recttransform

storm pine
# mighty basalt what is the easiest way to check if my camera is getting close to the end of my ...

Idk if it is the best option but I have a simple script with two public Vector2, to set min and max cameraPosition. And then I just manually set the values moving the camera and checking where I want my limits. and then clamping the position as show in this code ```cs
// Clamping a los límites establecidos
newPos.x = Mathf.Clamp(newPos.x, minCameraPos.x, maxCameraPos.x);
newPos.y = Mathf.Clamp(newPos.y, minCameraPos.y, maxCameraPos.y);
transform.position = new Vector3(newPos.x, newPos.y, transform.position.z);

quick dove
#

What am I doing wrong that my if statements arent making their own clamps?

#

is what I have but apparently it should do this

slender nymph
eternal falconBOT
valid roost
#

should i be worried

twilit pilot
valid roost
mighty basalt
# storm pine Idk if it is the best option but I have a simple script with two public Vector2,...

i dont think this is exactly what im looking for (might just be me not fully understanding the code). ive made 4 prefabs of tilemaps. when the game is launched, those 4 are on the screen next to each other. when the player (and therby camera) move towards the edge of the already instantiated tilemap, i need a new one to spawn. so hypothetically the player could walk infinitely left and new tiles would keep spawning

twilit pilot
rocky canyon
valid roost
#

there shouldnt be anything wrong since i've legit just added a pixel art pack so

rocky canyon
#

maybe he's never had that error

#

i frequently use stylized fonts..

#

and many of them are missing little things.. like ; or { or something similar

#

if u check out ur atlas / material / font asset stuff you'll see which ones are missing usually

twilit pilot
#

then they wont display correctly in your game if you're trying to use them - that's something to be worried about

#

but you do you

rocky canyon
#

its usually something u wouldn't use anyway.. if it becomes obvious that one of the characters are different.. u can just go and edit it then..

#

no need to make a new font asset for a character u wouldnt use anyway

twilit pilot
#

if you're seeing that warning you've tried to use it somewhere

rocky canyon
#

thats not true

twilit pilot
#

but you'll need to investigate where

rocky canyon
#

that error happens as soon as u create the asset

valid roost
#

i havent even started adding a tilemap

#

i havent even created an asset

#

🤷🏻‍♂️

rocky canyon
#

in the textmeshpro asset creator it'll tell u every character thats missing

#

ohh noo... im missing a what ever will I do

rocky canyon
valid roost
#

are there any good 2d movement videos i can watch

rocky canyon
#

if you haven't added a font.. then its probably a bug... or an issue w/ the editor

#

and can probably ignore it

rocky canyon
quick dove
#

So i went through that thing about getting it rdy for unity and the only difference I see is the attach to unity selection

#

visual studio = it

#

Oh, I see. the stuff on the bottom too

valid roost
#

does it involve flipping as well bc

rocky canyon
#

that helps u learn how a good one works.. as well as having some sample code

valid roost
#

whenever i complete the video

#

my sprite doesnt actually move left

#

i mean it doesnt flip

#

actually

#

i'll just watch the video you sent me

rocky canyon
#

u can use flipX variable..

valid roost
#

i see.

rocky canyon
#

or u can scale the graphics -1 on the x axis

#

most 2d tutorials will cover the flip part..

#

its the first bug u run into

valid roost
#

alright thanks

vale karma
#

im having trouble assigning a value to a scriptable object. I think im overthinking it, I just need and input fields text onEndEdit to be the value of the scriptable object string, so I can display it on another TMP_Text on the next scene. I got it displaying the scriptable objects text, but i keep getting an error bc im trying to reference a script not deriving from monobehavior

vale karma
#

!code

eternal falconBOT
slender nymph
#

you cannot use GetComponent to reference something that isn't a component

summer stump
vale karma
#
  public void SetInputFields()
  {
      pass = password.text;
      user = username.text;
      userInfo.Username = user;
  }
summer stump
#

Just drag it in

vale karma
#

okay lemme try

quick dove
#

Hmm and even after the updates when I do an if statement it isnt popping up the brackets

vale karma
#

ohhhh it workedd

#

thankya goodsir

vale karma
#

i could prolly help

#

lookup parallax effect unity

#

oh wait, not that haha

short hazel
vale karma
#

shoot, i forgot what its called, but the concept is in this 2d youtube vid "How to make your first Game in unity" with the flappy bird thing

quick dove
#

Yeah they must be placed in the brackets. The issue Im having is when following a tutorial, he hits tab to bring the text forward. typed if and when he does wiggly brackets pop up underneath with its own set of dotted lines to connect

#

mine isnt doing that

#

even though its set to

short hazel
#

Do you see the Unity types like Rigidbody, Transform in the completion list as you type, and are errors underlined red live as you type?

quick dove
#

errors are underlined yet

#

let me test the other part

#

yes to the second part

#

as you can see from that screen shot, if only goes two brackets deep

#

this shows that should go 3

#

when I do an if

short hazel
#

They invoked a snippet, by completing if and hitting Tab a second time

quick dove
#

AH

#

thank you!

short hazel
#

You can still type the brackets manually if you want, but snippets are faster to use. In the completion list their icon is a white square with a dotted bottom line

mighty basalt
short hazel
# quick dove

Second to last icon at the bottom of the completion list in this screenshot

vale karma
#

that would be like a raycast thing instead, are you in 3d space?

mighty basalt
#

i can send some screenshots if that makes understanding easier?

void thicket
mighty basalt
#

do i just create an empty and then when i spawn a new one, disable the old empty?

void thicket
mighty basalt
void thicket
#

You need both currently spawned tile bounds and currently visible bounds

mighty basalt
#

should the script be in my singelton, the grid, or on each prefab?

void thicket
#

If there is none yet then make one

mighty basalt
#

okay thx

#

ill see if i can make the thing with emptys work and come back here if i cant

eager citrus
#

How do I find a GameObject by a script attached to it?

void thicket
#

You need full component name

#

Or use QuickSearch.. though it was heavy when I last used it

scarlet skiff
#

im watching a tut on how to make a game multiplayer and when deciding to join as a host or client the oyutuber makes 2 seperate buttons for them, and also, he makes those buttons in the same scene that the client would join on.

What if i want it to check if there is a server, and if not, join as a host, otherwise, join as a client, and to do so in a different scene, like from main menu scene, you click play, looks for server, lets say it found one, then it joins you as a client i nthe game scene

timber tide
#

my eyes

vale karma
#

hahah

mighty basalt
#

how do i instantiate an object as a child of a parent object?

modest dust
mighty basalt
#

ahh mb

vale karma
#

usually you can find it by letting the IDE guess the next selection, or the list it gives, and the descriptions. It helps you learn about other uses of it too

#

If your lazy^^ hehe

quick dove
#

how do I stop visual from replacing Other with coother

#

what is coother

#

and why does it auto correct everytime?

jolly pendant
#

Any idea how to fix when Unity doesn't show the regenerate project files option?

slender nymph
#

make sure you have the visual studio editor pacakge installed and up to date

short hazel
#

And that your Unity version is recent enough, IIRC the older ones don't have that option

void thicket
jolly pendant
#

Ok, thanks

mighty basalt
#

when i instantiate my tilemap prefab, what part of that is instantiated at the given position? is it the center or like the bottom left? hope that made sense

slender nymph
#

set your tool handle to Pivot and open the prefab and select the root object. where the tool handle is at is the 0,0 position

quick kelp
#

if anyone here remembers me from asking for help yesterday i made a video on what my problem was

will provide reply context if needed

rare basin
#
public class SteeringWheelMapper : MonoBehaviour
{
    public TMP_Text debugText;
    public Transform steeringWheelTransform;
    public float maximumDegrees = 270;

    public float MapRotationToValue()
    {
        float rotationZ = steeringWheelTransform.localEulerAngles.z;
        float mappedValue = rotationZ / maximumDegrees;

        return mappedValue;
    }

    void Update()
    {
        float mappedValue = MapRotationToValue();
        debugText.text = mappedValue.ToString("F2");
    }
}

I am trying to remap the localEulerAngles.z into input from (-1;1) based on the value. So -270 is -1 and +270 is 1. It is working fine when turning the steering wheel right (correctly maps the values) but when turning the steering wheel left, the values are positive, not negative, why is that

#

is it because the localEulerAngles are from (0;360)?

mighty basalt
slender nymph
#

click the root object. and look at the scene view

mighty basalt
slender nymph
#

yes

mighty basalt
#

okay. can i change that somehow?

slender nymph
#

move your tilemap

#

or place the tiles again so that it is in the center (or where ever you prefer it to be relative to the tiles)

mighty basalt
#

okay thx

hushed hinge
short hazel
#

Attack script, line 14. You pass null or an empty string to CompareTag()

#

This is not allowed

short hazel
#

On one of your objects, attackTarget or attackBigTarget (or both) has no value in the Inspector

#

Find all objects with this script on, and correct the mistakes

hushed hinge
#

ok

short hazel
#

Search for: t: Attack in the Hierarchy's search bar and go through all results.

#

Also check prefabs

hushed hinge
short hazel
#

Same issue - look at the stack trace, it contains the file and line of code that triggered the error:

#

Here, ProjectileAttack, line 28

hushed hinge
#

ahh, the attackBigTarget

short hazel
#

It can also be attackTarget, note that you have two calls to CompareTag() on the same line

hushed hinge
#

huh? Enemy and BigEnemy can be on attackTarget?

short hazel
#

No I mean you have two variables, attackTarget and attackBigTarget, these may have no value in the Inspector

#

It's not about which script is attached to the object (the error tells you which scripts the errors originate anyway)

#

There are of course multiple scripts with these variables (you showed two) so go through each error, each stack trace and fix them all

hushed hinge
#

well the reason why i call ig BigEnemy because i thought of bigger enemies with 3 health, lost most platform games

short hazel
#

I don't know why you're talking about some "BigEnemy"

hushed hinge
#

I did this instead

short hazel
#

Ignoring the problem entirely I see

#

As long as it works, I guess
You just had to go to the Inspector and fill "BigEnemy" there in the field, but seems like it's too complicated to do

eager wolf
#

every time i move an object using Input.mouseposition; the Z is -79.9999 (Unity2D)

Why is that?

hushed hinge
slender nymph
storm pine
eager wolf
#

none of the parents have -80 either

short hazel
#

If that's a UI object, you should change the RectTransform's anchoredPosition for best accuracy

ivory bobcat
eager wolf
#

i probably have some other piece of code interfering tbh

slender nymph
eager wolf
#

otherwise this makes no sense

eager wolf
slender nymph
slender nymph
#

Is this a UI object?

eager wolf
#

yes

slender nymph
#

Why are you converting that to world space

eager wolf
#

because if i don't, it goes offscreen

#

i use pixel perfect, idk if that's why, but my screen resolution is MUCH smaller in game than on my pc

zenith cypress
#

ScreenToWorldPoint for perspective cameras needs z to be non-0, such as the camera's nearClip plane value on said camera.

eager wolf
#

i guess i kinda managed to bootstrap fix it by setting z to 8 rather then 0 lol

deft grail
#

also that tutorial or others should cover that i think

hushed hinge
frigid sequoia
#

Maybe I am dumb, but is there a way to set the animation speed of an animation clip without an animation controller?

frigid sequoia
#

I just want to play a one shoot on a trigger but it needs to have a variable speed

deft grail
#

use Input.GetAxisRaw

frigid sequoia
polar acorn
frigid sequoia
#

The animation component

polar acorn
# frigid sequoia

You should not be using the legacy animation component. Use an Animator Controller

frigid sequoia
#

I don't need an animator controller to play just a single clip, is unnecessary

void thicket
small mantle
#

I am making a game where there are a wide variety of Characters. These Characters all have the same stats, but not values for them. For example they all have jumpForce, moveSpeed, attackCooldown, and attackDamage. I am wondering how I can make a PlayerStatManager script that I could change overall stats of the Character there.

deft grail
void thicket
small mantle
frigid sequoia
void thicket
small mantle
void thicket
small mantle
void thicket
# small mantle per character.

Anyhow you would expose this CharacterStat component per character and have it manage the attached character’s stat, so it would have variables or dict for stat type

frigid sequoia
small mantle
frigid sequoia
#

Just make a script that holds parameters for all the stats, and make it that on awake, it sets parameters of all other scripts, you just need a reference for them

frigid sequoia
small mantle
void thicket
#

Single responsibility

queen adder
summer stump
frigid sequoia
#

Okey, sure

small mantle
frigid sequoia
summer stump
frigid sequoia
#

What issue does it has?

void thicket
summer stump
summer stump
open gull
#

Hi, could someone tell me how to do this in a more intelligent way pls?

look, it's kind of functional, but it doesn't seem to be the smartest way to do it, especially when I still have to check if the gameobject is being occupied or not

small mantle
void thicket
#

But I agree with your point that Mecanim is tedious for small simple animations

frigid sequoia
ripe shard
void thicket
vale karma
#

brooo i need some jesus organizing this code XD oh my ogd

north kiln
shell ice
ripe shard
shell ice
#

hello , this is sliders that exist already in unity , i want to use them as a gameobject , i want to instantiate them , destroy them , and position them with a transform just like normal gameobjects

deft grail
#

you have Afterburners inside of Update

#

it shouldnt be inside of there

open gull
deft grail
#

you also need to actually call the method somewhere

north kiln
#

Never call the function, and also just the word "print" randomly in there

deft grail
#

sure, or move it outside and actually call it and make it run

deft grail
#

each object has a Transform

north kiln
#

Well, that's not how you do that either

void thicket
deft grail
#

you just said whats wrong

north kiln
#

If you're not getting error highlighting and autocomplete, you need to configure your !ide

eternal falconBOT
deft grail
#

and how would you do that

ripe shard
deft grail
#

ok but... what code

twilit pilot
deft grail
#

how would you print something

#

ok, so you dont just write print and expect it to work

#

you tell it what to print

#

the same concept applies here in Unity

open gull
hushed hinge
twilit pilot
# open gull I don't think this is a sustainable way, since you would have to create a game o...

so you're happy with having a grid for each possible card position?

having a GameObject just for an anchor point to represent each slot isn't too expensive, though looping through each is quite unnecessary. You should probably define a 2d array that contains every Node/anchor, and write a function that directly maps a cursor position (x, y) to the closest node directly. If it's not clear how to proceed I can expand a bit

void thicket
open gull
twilit pilot
# open gull To be honest, I wish it wasn't like this (a grid for each possible position of t...

I mean it works, and looping through 30 or so positions is really not a lot, especially if you're only doing it in response to user input.
Usually for grids though you'd want to have some kind of array, GameObject[,] and to write a few functions that transform coordinates from where you click/world space/screen space x,y to which grid cell it is i,j and vice-versa
If you didn't want a grid at all, just let the cards handle their own position - they are already their own objects. It's not clear what behaviour you'd like for the game and why that wouldn't work though. Each card can have its own event handling for clicks, based on a raycast from your cursor position (if you're using EventSystem most of the awkward stuff is done for you)

vernal crow
#

Yo boys I need some help

vernal crow
#

Just let me remember

open gull
vernal crow
#

Okay so I’m trying to make the player transfer to another scene (inside house) but I can’t figure out how to make the inputs for it. I made a box collider and made it ignore the player so that I could make that a trigger field all I need is the code for something like that

rich adder
#

then switch scene

vernal crow
#

Actually I’ll go to google

rich adder
#

unity has specific methods for triggers

#

it should come right up

vernal crow
#

Thank you sir

silk fossil
#

bro this makes no sense,

#

projectile is literaly defined

#

HOW IS IT NOT DEFINED

#

im trying to destroy the object is it has the tag Projectile once it hits player

#

as you see in that code

void thicket
silk fossil
#

what that

void thicket
#

General solution: just don’t use tags

#

It sucks

silk fossil
#

it detects the collision with player using tags

polar acorn
silk fossil
#

but im trying to remove the object projectile once it hits it

rich adder
static cedar
#

I have yet to use one.

rich adder
#

GetAxis

polar acorn
#

And an animator

frigid sequoia
#

These parameters are meant to no be used, since they are jut to show for debug purposes. Is there a way to tell the script that so it doesn't show as a yellow error?

polar acorn
#

Oh wait nevermind they're particles, different .Play

rich adder
#

GetAxis uses a float, so you can check if its not 0
also gives you Horizontal (AD/arrows) or Vertical (WS/arrows)

flint python
#

I am using vscode, is there a way to rename script that will auto rename the class name as well?

frigid sequoia
rich adder
#

yeah if you use GetAxis it will be literally 2 lines

#

what the heck is ~=

#

lol

#

you mean != ?

#

ah ok . Yes ! means NOT

teal viper
#

In C#

#

And many other C-like languages

hushed hinge
rich adder
#

are you sure script is running ?

#

was it working before changing

#

are you sure you want Play instead of Emit

#

try it

#

its probably because it being constantly called

#

before you had KeyDown

#

which is single frame event

#

now you're doing basically GetKey

#

which is held-down-like behavior

#

what is the error

#

yes emit wants the amounts of particles you want to emit at once

#

start with 1?

teal viper
#

As many as you specify in the particle emitter settings.

rich adder
#

Play just plays whatever you have set there in main component

north merlin
#

i got a situation. I have x and z axis movement and would like to use the magnitude of the button press to drive a blend tree but if i move diagonal i get a value of two rather than the higher value between the button press.

rich adder
#

You can try the other way with .Play()

#

just put if(audioSource.isPlaying) return; before it

void thicket
rich adder
hushed hinge
teal viper
rich adder
silk fossil
#

tnx

teal viper
eager wolf
#

how do i get text to light up? If i do this (which works on images) it shows as full black (even with lighting)

rich adder
#

also use TextMeshPro
a sprite Material on a text is probably not very good idea btw. Everything should be changed in the appropriate shader, again TMP

teal viper
teal viper
rich adder
#

why is direction an int lol

teal viper
#

They set it to 1, -1. I guess the intention is multiply the velocity direction.

rich adder
#

oh that makes sense ig

#

personally would rather Flip the whole player 180 on the Y

#

keeps everything properly as transform.right usually

eager wolf
rich adder
eager wolf
rich adder
eager wolf
eager wolf
#

hope this makes more sense

rich adder
#

ohh

#

maybe you can use the mesh version

#

or maybe masks

eager wolf
atomic sierra
#

how do you guys practice with unity

#

like the unity interface and knowing what to find and what to use

rich adder
hushed hinge
rich adder
#

jk

#

use the Manual or Docs

rich adder
eager wolf
hushed hinge
#

here https://gdl.space/ayaluzozav.cs. but since it's stoo long and it can be hard for you to find the flipmodel, here

private void FlipModel()
    {
        if(  (Input.GetAxisRaw(_horiz) > 0 && _isFlipped)
           || (Input.GetAxisRaw(_horiz) < 0 && !_isFlipped)
          )
        {
            _isFlipped = !_isFlipped;
            Vector3 scale = transform.localScale;
            scale.x *= -1;
            transform.localScale = scale;
        }
    }
rich adder
frigid sequoia
#

Isn't this supposed to return the opposite rotation to the one of the object with the script?

#

Cause it is not doing that

rich adder
hushed hinge
frigid sequoia
rich adder
void thicket
#

Inverse of identity quaternion is identity quaternion

frigid sequoia
#

Is literally a quaternion method

rich adder
#

make sure they are what you think they are

void thicket
#

Nothing to do with 'direction'

frigid sequoia
#

I mean I know the input and the output cause I am checking the rotation of both objects, but they don't even make sense to me

void thicket
#

Rotation is not defined with single vector

#

If you want vector math, rotate forward vector with your quaterion and modify it to get new quaternion

frigid sequoia
#

Rotation of the projectile that is instantiating the particle // Rotation of the instantiated particle using Inverse

#

Is making the negative in eulers or what?

rich adder
#

I mean it is inverting it technically lol

#

its probably not doing what you think

void thicket
#

I don’t think messing with euler will give you preferable result

frigid sequoia
#

That's clearly not the opposite of the projectile rotation...

hushed hinge
# rich adder what ? no.. You literally wrote this `int` as direction, but you're not using it
IEnumerator SpawnProjectileAfterDelay()
    {
        yield return new WaitForSeconds(shootingDelay);

        int direction = spriteRenderer.flipX ? -1 : 1;

        GameObject projectile = Instantiate(projectilePrefab, projectileSpawnPoint.position, projectileSpawnPoint.rotation);

        ProjectileAttack projectileController = projectile.GetComponent<ProjectileAttack>();
        if (projectileController != null)
        {
            projectileController.SetDirection(direction);
        }
    }
``
void thicket
#

forward * rot * -1 this is probably the direction vector you are looking for

rich adder
rich adder
void thicket
#

Then create new Quaterion with it, could be LookAt with up vector

hushed hinge
rich adder
#

Your set Direction doesn't do anything with the value passed it

rich adder
#

think for a moment about your bullet script

#

How do you think direction is doing anything here

void thicket
# hushed hinge huh?

You know what just do
transform.forward = -transform.forward and see if that is what you want

rich adder
#

different person, with different issue lol

void thicket
#

Why was I mentioned

#

Lol

rich adder
#

they probably thought you sent the earlier one to them

frigid sequoia
hushed hinge
frigid sequoia
#

And the bullet is basically just spawning and moving forward each frame, so that's what the rotation does

void thicket
#

Setting transform forward will change rotation

hushed hinge
rich adder
#

if you have trouble clicking pause on time, you can use Debug.Break after Instantiate to automatically pause

#

then show both the shootPoint gizmos and bullet selected gizmos

hushed hinge
rich adder
hushed hinge
rich adder
#

also put it in Pivot mode not Center mode

#

never do Center mode to accurately config your character parts

void thicket
#

Center mode is so rarely used for programmers

#

You almost never want it

rich adder
#

yeah I mostly just use Center mode when Extruding meshes in Probuilder

hushed hinge
frosty hound
#

Center is the pivot mode.

rich adder
#

you always want it on Pivot

#

anyway so your bullet is going Right still ?

hushed hinge
#

there, pivot mode

hushed hinge
rich adder
hushed hinge
#

yeah

frigid sequoia
#

Man, I don't know what is wrong. I changed it to Quaternion.identity just for testing and shoot at different angles agaisnt some walls. And added a Debug.Log script to the particle to tell its rotation. Isn't Quaternion.Identity supposed to be always the same?

void thicket
#

identity should be same so something else is changing your rotation

frigid sequoia
#

Oh, ok, I am fucking dumb, there was something wrong with some old logic for bounces

#

This does work now, but I kinda annoyed I cannot set that directly in the instantiate rotation

void thicket
#

Quaternion.LookRotation

frigid sequoia
void thicket
small mantle
#

Is there a way to set a speed of an animation in code? I am trying to make an animation length slower or faster depending on the attackCooldown. How can I achieve this?

nimble apex
eternal needle
small mantle
small mantle
eternal needle
#

It is a speed multiplier

nimble apex
small mantle
#

I'll try these suggestions thank ya.

stuck crest
#
 public event EventHandler<OnDeliverySuccessEventArgs> OnDeliverySuccess;

public class OnDeliverySuccessEventArgs : EventArgs
{
    public float amount;
}

OnDeliverySuccess?.Invoke(this, new OnDeliverySuccessEventArgs
{
    amount = recipeSO.price
});



different script

private void DeliveryManager_OnDeliverySuccess(object sender, EventArgs e)
{
    moneyHandler.SetMoney(this,e.amount << error shows up here "Event args doesnt contain a defination for amount );
}
#

hi guys

#

my problem is that

#

my event subscrber function isnt getting the event args

#

for some reason

cosmic dagger
#

EventArgs does not have a definition for amount, but OnDeliverySuccessEventArgs does . . .

stuck crest
#

ahh ok

#

but how do i implement it

#

this isnt working

summer stump
stuck crest
#

wait

#

not this

stuck crest
cosmic dagger
summer stump
#

Because it will if done right

stuck crest
summer stump
stuck crest
#

the type or namespace cannot be found

cosmic dagger
#

where does the class exist?

stuck crest
#

in another script

#

i have done this before

#

with other events

#

it shows the error in this one only

cosmic dagger
#

then you need to correctly access the type . . .

summer stump
cosmic dagger
#

if it's inside a script, then it's nested . . .

cosmic dagger
summer stump
summer stump
cosmic dagger
#

access it correctly from the parent class or place it in it's own file . . .

stuck crest
#

im sorry im a bit confused , how do i like do this

stuck crest
cosmic dagger
#

if it's inside of a class, then you need to access the class first before you can access the child class, no?

#

the same way you're trying to access e.amount. amount is a field of e (which is OnDeliverySuccessEventArgs) . . .

quick kelp
#

is it a bad idea to use binary formatter for a single player game

cosmic dagger
# stuck crest how do i acces it correctly

OnDeliverySuccessEventArgs is a child class nested inside of another class. you need to access the other class first (using dot notation), in order to get access to the child class . . .

quick kelp
#

trying to get rid of my dont destroy method of persisting items in game cause that seems to be whats causing the problem

#

and after a day of debugging and potential fixes im still at square 1

#

so im just going to make a room manager

eternal needle
#

🤷‍♂️ might be better to say what your actual problem is instead of asking about solutions for something we are unaware of.

#

There is a major difference between DDOL and saving data to file, which i assume was the goal with asking about binary formatter.

quick kelp
#

and after todays debuggin its either the onItempickup in my inventory controller or the slots script itself

cosmic dagger
eternal needle
#

well you posted a video and said "if anyone remembers the problem". theres no way anyones gonna help you in such case...
when you post, there should be full context

quick kelp
#

yeah thats my bad ive been stressed trying to figure this out

eternal needle
#

not sure about other people, but i especially dont really like watching videos to help people. half the time the video is useless. Like "hey guys my character doesnt move". then its a 3 minute video of them scrolling quickly through code, and then showing their character not moving.

quick kelp
#

ok i get that

eternal needle
#

it is a lot simpler if you can isolate the specific issue and post code related to it. If you arent able to isolate it at all, (which some problems are hard to isolate), then you likely just need to add more debugs. see what values are, and if they arent what you think it is then that is now relevant code

quick kelp
#

but i literally ust recorded what the problem was i literally got to the point

summer stump
quick kelp
#

if you leave then come back the item will not show up and in Debug.Logs

#

does not even register that your item has been slotted

#

tho the pickup script does still work

feral moss
#
    public void Restart()
    {
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                Destroy(gridMemory[i][j]);
            }
        }
        gridMemory.Clear();
        tilesLeft = width * height - mines;
        GenerateGrid();
    }

So I wrote this function for resetting a grid I generated, gridMemory is a List<List<Instance of Prefab object>> object where the exterior list is size width and the interior is size height

#

Initially the nested for loop wasn't even there because I thought the Clear would take care of it, but after that didn't work I tried deleting every object individually and that also did nothing

#

So I'm confused

summer stump
#

Oh, edited. Nm

eternal needle
#

did you debug if this code was actually running?

feral moss
#

It is running

#

What happens is it generates a second grid but doesn't delete the first

#

So I've got overlapping tiles that don't work

#

At least as far as I can tell

#

It's Minesweeper

teal viper
feral moss
#

Are they just being cleared from gridMemory but not from the scene somehow still?

teal viper
eternal falconBOT
feral moss
#

Uh sure

#

Tile.cs

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;

public class Tile : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField] SpriteRenderer Renderer;
    [SerializeField] public bool hidden = true;
    [SerializeField] public int val = 0, x, y;
    [SerializeField] Sprite revealed;
    [SerializeField] public GridManager grid;
    [SerializeField] private bool isClicked = false;
    void Start()
    {
        revealed = grid.getSprite(val);
    }

    // Update is called once per frame
    void Update()
    {
        if (!hidden)
        {
            Renderer.sprite = revealed;
            if (val == 9 && !grid.lost)
            {
                grid.Lose();
            }
        }
    }
    public void OnMouseDown()
    {
        if (!isClicked)
        {
            isClicked = true;
        }
    }
    public void OnMouseExit()
    {
        isClicked = false;
    }

    public void OnMouseUp()
    {
        if (isClicked)
        {
            hidden = false;
            if (val == 0)
            {
                grid.clearSurrounding(x, y);
            }
            isClicked = false;
        }
    }

    public void CheckSurrounding()
    {
        hidden = false;
        if (val == 0)
        {
            grid.clearSurrounding(x, y);
        }
    }
}
#

CameraScript.cs

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

public class CameraScript : MonoBehaviour
{
    [SerializeField] private Camera camObject;
    [SerializeField] private float sensitivity;
    [SerializeField] private GridManager grid;
    [SerializeField] private ButtonScript button;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A) && camObject.transform.position.x > 0)
        {
            camObject.transform.Translate(sensitivity * -1, 0, 0);
        }
        if (Input.GetKey(KeyCode.W) && camObject.transform.position.y < grid.GetHeight())
        {
            camObject.transform.Translate(0, sensitivity, 0);
        }
        if (Input.GetKey(KeyCode.D) && camObject.transform.position.x < grid.GetWidth())
        {
            camObject.transform.Translate(sensitivity, 0, 0);
        }
        if (Input.GetKey(KeyCode.S) && camObject.transform.position.y > 0)
        {
            camObject.transform.Translate(0, sensitivity * -1, 0);
        }
    }
}
teal viper
#

What you want to destroy is component.gameObject

feral moss
#

Oh ok

#

That's what I get for using var when instantiating

#

I didn't know exactly what I was working with

#

Thanks

teal viper
#

But yeah, if you didn't use var it might've given you a clue

feral moss
#

Yeah I created the initial GenerateGrid() with a youtube tutorial and then customized it to be for the game I was working with, but I didn't change that part

quick kelp
#

https://hastebin.com/share/vocexepuha.csharp
InventoryController

https://hastebin.com/share/irepaludoy.csharp
ItemSlot script

Short explanation: if it grab the items before leaving the room they show up in my inventory ui and debug log tells me the item data has been filled in but if i leave before grabbing them and come back the log does not fire off one but

note: the items are children to a empty game obj with a dontdestroy script to keep things persistent

#

tried to record a shorter video the best i could

rocky gale
#

how do i make particles fly a different direction

slender nymph
rocky gale
#

posted there 5 hours ago

slender nymph
#

then don't crosspost. and maybe provide literally any details about what you are actually trying to achieve and maybe someone will take the time to help you

timber tide
#

Ill be real. I saw your post but I literally needed any detail about what you were actually trying to achieve

rocky gale
#

ok

slate haven
#

Hi, I need help in object pooling

#

anyone online?

slender nymph
slate haven
#

basic ethics

#

if someone is available to help me on Object Pooling, asking very kindly

slender nymph
#

did you even bother reading the page that was linked

cosmic dagger
#

no, ask what issue or problem you are having. post the code in question, and any errors you have . . .

slate haven
slender nymph
#

well you won't solve it until you actually ask your question

cosmic dagger
slate haven
slender nymph
#

you have now spent 3 minutes just beating around the bush instead of asking your question. it is entirely possible your entire issue could have been solved by now

cosmic dagger
#

people are less inclined to help without actual information. asking about a general topic steers them away because they don't know the scope, skill required, or time complexity of the problem . . .

slate haven
slate haven
cosmic dagger
#

still, we're at square 1 . . .

slate haven
#

i want to share a video

#

do i share it directly here

slender nymph
slate haven
#

or any embedded sites

slender nymph
#

the answer to that should be pretty obvious.

slate haven
#

yes ofc, but apparently i came to know some people wont be able to see the video if i directly share it

#

in other server

#

thats the reason im asking is there a specific rule here to post a video

#

like u paste the code into an embedded one

#

like that

slender nymph
#

provided it is properly embedded it doesn't matter whether you share the video directly or a link. just ask your fucking question if you want help

slate haven
molten dock
#

if ur annoyed by it why not ignore the initial question

#

as opposed to arguing other nothing

cosmic dagger
slate haven
#

i would never go outta my way to add a derogatory term to someone's question

#

even if thats the most silly question

slender nymph
cosmic dagger
#

i was speaking about the friendly box . . .

slate haven
slate haven
#

anyways, i dont wanna argue more, im gonna post my question, if anyone is available any help is appreciated

molten dock
#

💀

topaz mortar
#

Since yesterday (at least that I noticed) when I double click an error in my Console, it takes me to the wrong file/line number?

teal viper
topaz mortar
#

Takes me to CombatController line 441, which does call Inventory

#

the error is not hard to fix, it's just weird, I've noticed this a few times now, it just takes me to a random place instead of the error line

slender nymph
#

well that isn't really a random place, it is part of the stack trace for the error. it is odd that it takes you there though 🤔

topaz mortar
#

but the actual error is on Inventory line 36

#

yeah this one is not random, think I had worse cases yesterday, but maybe it was similar

#

it worked perfecly for months, started noticing this only yesterday

rocky gale
teal viper
slate haven
#

Problem: The coins are getting collision detection right and they are getting Deactivated properly (ig theres no array of coins thatswhy). Now Vehicles, Pickups are arrays. And When I collide with them, the collision doesnt seem to happen especially with vehicles. I am really confused about whats happening here. Also The Fps are dropping mid game

ObjectPooler script: https://hastebin.com/share/dubecaheji.csharp

My Normal Trigger Script format:

   {
      if(collision.gameObject.tag == "Coins")
       {
           scoreValue.score += 50;

           //Destroy(collision.gameObject);
           if (collision.gameObject != null)
           {
               op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
           }
       }

       if (collision.gameObject.tag == "Enemy")
       {
           if (!hasShield)
           {
               hasCrashed = true;
               crashCount++;

           }

           else
           {
               StartCoroutine(ActivateShield());
           }
           //Destroy(collision.gameObject);
           if(collision.gameObject != null)
           {
               op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
           }
           
       }

   }```
topaz mortar
#

unity auto updates, I think there was a big update a week or two ago? might have been since then

slender nymph
#

unity does not auto update

#

even packages need to be updated manually in the package manager

topaz mortar
#

ah maybe it asked then dunno lol

#

I know I updated unity a few weeks back with the new version control thingie

slender nymph
#

make sure your visual studio editor package (or the rider one if you use rider) is up to date and regenerate project files. then restart both unity and your code editor to see if that makes any difference

topaz mortar
slate haven
topaz mortar
#

lol no

slate haven
#

uhm pls do watch it

#

it explains

topaz mortar
#

no thank you

cosmic dagger
slate haven
topaz mortar
#

remember that tomorrow when you come back to ask it again 😉

slender nymph
#

dang, dunno what it is then 🤷‍♂️
are you sure you're double clicking the actual error message and not perhaps accidentally clicking the other line in the stack trace?

slate haven
cosmic dagger
slate haven
#

shall i share it on google drive ?

slate haven
teal viper
teal viper
#

Or maybe YouTube, I don't know.

slate haven
#

imma do vpn

#

wait, i will share the whole again

slate haven
#

Problem: The coins are getting collision detection right and they are getting Deactivated properly (ig theres no array of coins thatswhy). Now Vehicles, Pickups are arrays. And When I collide with them, the collision doesnt seem to happen especially with vehicles. I am really confused about whats happening here. Also The Fps are dropping mid game

ObjectPooler script: https://hastebin.com/share/dubecaheji.csharp

My Normal Trigger Script format:

   {
      if(collision.gameObject.tag == "Coins")
       {
           scoreValue.score += 50;

           //Destroy(collision.gameObject);
           if (collision.gameObject != null)
           {
               op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
           }
       }

       if (collision.gameObject.tag == "Enemy")
       {
           if (!hasShield)
           {
               hasCrashed = true;
               crashCount++;

           }

           else
           {
               StartCoroutine(ActivateShield());
           }
           //Destroy(collision.gameObject);
           if(collision.gameObject != null)
           {
               op.DeactivateGameObject(collision.gameObject.tag, collision.gameObject);
           }
           
       }

   }```


I have attached the video as well:
https://streamable.com/bfn2ac

Watch "2024-05-13 10-10-35" on Streamable.

▶ Play video
cosmic dagger
opaque hinge
#

Hello, I am working on a game right now and I created two scenes. A Main Menu scene and my game scene. When I build the game from the main menu scene, I can press a start button that loads my game scene and properly runs the game. I then can pause while in the game and press the quit button, which properly loads my main menu. However, when I try to start the game again from my main menu, the game doesnt properly load and I get a bunch of errors about trying to access objects that have been destroyed

cosmic dagger
molten dock
#

Do the trucks have trigger collider

slender nymph
cosmic dagger
plush hound
#

hey, i'm trying to use physics2d.istouchinglayers to no avail and i'm not sure why. i've looked through online forums and documentation, but i can't seem to find a solution.

colliders in question: circlecollider2d and polygoncollider2d
both colliders are on the same layer

any help would be greatly appreciated.

plush hound
#

sorry

slate haven
#

but why im facing fps drops?

#

even with object pooling which gives performance

opaque hinge
slender nymph
#

do you call DontDestroyOnLoad anywhere in your code?

opaque hinge
#

no

slender nymph
#

you can also share the code for the object that is experiencing this issue

molten dock
slate haven
slate haven
#

I really dont know why is the lag happening and what is causing it to be

molten dock
#

It looks fine to me what am I missing

slate haven
#

When I was doing instantiation/destroy, then also I was facing this lag, And now with object pooling im facing same

slate haven
molten dock
#

If you’re moving the cars with rigibody

#

Make sure the part of the code that actually moves it is in fixed update

slate haven
#

but i m not using the rigidbody to move

#

im using transform.position

molten dock
#

Then don’t do that

opaque hinge
slate haven
#

transform.position -= new Vector3(0, Speed * Time.deltaTime, 0);

molten dock
#

it only applies to rigibody rly

slate haven
#

oh

slender nymph
opaque hinge
#

MissingReferenceException: The object of type 'Tile' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Component.GetComponent[T] () (at <f7237cf7abef49bfbb552d7eb076e422>:0)
BattleSystems.GenerateGrid () (at Assets/Scripts/BattleSystems.cs:108)
BattleSystems.Start () (at Assets/Scripts/BattleSystems.cs:26)

MissingReferenceException: The object of type 'Enemy' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Tile.OnMouseEnter () (at Assets/Scripts/Tile.cs:22)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

slate haven
slender nymph
molten dock
#

No way for me to tell why

#

The code is very normal

opaque hinge
molten dock
#

Well maybe it’s the corutine

#

Idk tho

slate haven
#

lemme share the performance video

slender nymph
teal viper
slate haven
slow pecan
#

Hey I got a question. Im trying to use unity for my school finals project, and I am trying to create a teleporter that allows you to exit an area after all the enemies are gone. I get that the tag length has to be 0, but is there a way to differentiate between two rooms? Like have the enemy tag and a room number tag? if so how would i do that?

rich adder
#

just keep an index

slow pecan
#

ty

rich adder
cosmic dagger
#

look into an int, come back with an integer . . .

slow pecan
#

ok. I am not too sure where I would find the seperation between rooms, but I think I can try it by having entities labeled "room #" and adding enemies on spawnable tiles at that entity on the arraylist, seperating them

#

sry if description is wonky, not too sure how to describe well

rich adder
#

the index is the separation

hasty sleet
#

If the rooms are stored in a list, then as navarone says, the index of the room can be used to point to different rooms. If they are not stored in a list, then you can tag game objects as Room1 and Room2 and similar

rich adder
#
public class Room : MonoBehaviour
{
    public int Index;
    public void GetRoomInfo()
    {
        Debug.Log($"Is room #{Index}");
    }

    //Do more stuff with Room
}
hasty sleet
#

I like that approach ^

slow pecan
#

mmm thats makes since ty. but I got one last question. Can tags have subtags or is that not a thing in unity?

rich adder
#

eg you could store a list of enemies, so each room can have different amounts

rich adder
#

start getting into a habit of learning Components

#

since unity is Component based

hasty sleet
wintry quarry
#

They're extremely limited

#

Mostly a thing for prototyping

slow pecan
#

ok ty. I will look into it a lot more. Glad that i got all this help so fast

hasty sleet
#

To determine if an object is of a certain type, you can check its layer, or TryGetComponent<ComponentType>()

#

So if you want to check if Room1 is empty, then perhaps you store a reference to the CurrentRoom in the teleporter, and the teleporter calls Room.IsEmpty(), and if it's true, allows the player to teleport, else does nothing.

slow pecan
#

Would you recommend getting the number of children under an enemy storage from the hierarchy?

hasty sleet
#

Tags accomplish the same thing in a very hardcoded style, so it gets very difficult to scale

#

That can be one way to do it

slow pecan
#

I will look into trygetcomponent too

hasty sleet
#

If a room has a GameObject container for Enemies, and it has zero children, that can imply that the room is empty

#

You can also draw a box over the room and check for enemy collisions

slow pecan
#

oh lmfao never thought of that

hasty sleet
#

Or you can manually assign the enemies in the inspector to the Room in a List<Enemies> data structure and then check if the list is empty

slow pecan
#

oh yeah that makes since too

hasty sleet
#

These are all possibilities

#

Whichever one you choose comes somewhat down to preference