#πŸ’»β”ƒcode-beginner

1 messages Β· Page 153 of 1

edgy fox
#

is there a way to execute a command next frame?

rich adder
edgy fox
acoustic violet
#

what should i set Times Clicked to if i cant set it as 0 if its not an Int

rich adder
polar acorn
strange granite
#

Hello

acoustic violet
#

well i tried to set it to 0, but because its Text im unable, so what should i set it to

rich adder
#

TimesClicked is clearly an object (assuming a Text object)
but its not assigned, therefore Null at runtime when you try to use something from it .text

strange granite
#

private Vector3 offset = new Vector3(16, 3, -9); how can i put dots there Vector3(16, 3, -9) without error (exmpl 16.5, 3.23, 9,30 this is error)

polar acorn
polar acorn
rich adder
#

for float

acoustic violet
#

how should i set TimesClicked to a reference of a Text Object

rich adder
#

dont copy the code, just look at the example

strange granite
acoustic violet
#

This is what its been set as

rich adder
#

search hirerchy for t:MouseInputProvider

acoustic violet
#

okay i think i found the issue now

#

thanks for the help

edgy fox
#

what causes this?

#

I just get it occasinoally

rich adder
#

if not that, one of your assets/prefab would be missing a script / broken meta

edgy fox
rich adder
#

maybe you just noticed?
its a warning btw not an error

faint osprey
#

how do i start a timeline through script

rich adder
#

imagine this thing called google..

#

imagine you type words

#

magic

faint osprey
rich adder
#

orly ?

faint osprey
rich adder
#

you asked a better google question on this discord and not the search itself ,wild πŸ˜†

#

acivate timeline through bool is very strange

#

the two aren't much related

#

just saying keywords matter, if you search what you wrote on DC

faint osprey
#

damn

#

thats crazy

supple citrus
#

So when you declare a rect, it uses the 4 parameters as described in the upper image

#

But how do i declare one using xmin etc?

#

Theres an easier way then doing
Rect test
test.xMin = ...
test.yMin = ...
...
right?

tender wren
#

I think its more like
test.min = Vector2 (xmin,ymin);
test.max = Vector2 (xmax,ymax);

supple citrus
#

But is there a way to just do it in one line like there is with the upper image

#

Rect test = new Rect(xmin, xmax, ymin, ymax)

#

because the website is stating it as if there is

tender wren
#

public Rect(float x, float y, float width, float height);
public Rect(Vector2 position, Vector2 size);

#

the mins are the start

#

the size is the ends

#

min and max

supple citrus
#

the size is the distance from x to the end point

acoustic violet
#

Why cant i refrence the code in SBulbUp if its a public class?

supple citrus
#

i just want to define the x and y point themselves

tender wren
#

I think I may be confused, how does:

public Rect(float x, float y, float width, float height);

not work for that?

supple citrus
#

because if x = 1 and width = 2
the rect x coords would be 1 and 1+2

#

but i want to declare it using x=1 and x=3

#

where i input 1 and 3

tender wren
#

public static Rect MinMaxRect(float xmin, float ymin, float xmax, float ymax);

supple citrus
#

oh yeah thats exactly what i was looking for

#

ty

ivory bobcat
#

Also, what does the error say?

acoustic violet
#

Thats the SBulbUp code

gaunt ice
#

but this is not SBulbUp class

acoustic violet
#

oh my god

#

i found the issue

#

dammit

ivory bobcat
#

So the class type isn't sbulbup

acoustic violet
#

yep

#

im sorry

#

thanks for helping me realize

supple citrus
#

ah

#

Ive got coordinates of an object that I want to be a vertex for my Rect

#

But the transform.position of my object uses a dif coordinate system to Rect

#

As in, the the width of my rect is 12.5

#

but ingame thats really small

#

because im guessing declaring a rect uses pixels instead of whatever coordinate system the objects use?

#

How do i convert them

#

ohh is that was ScreenToWorldPoint does

#

gee wiz

normal fossil
#

Hello, is anyone familiar with Pool It? Do I manually have to add it to the pool manager for each prefab, or is there a quick way I'm missing?

#

Just trying to speed up my building system, my building system uses instantiation and causes big lag spikes. Maybe I am missing something.

#

It seems based on the profiler, it is causing a lot of lag

#

Wow, I figured it out. I always do when I ask for help. Its my UpdateBag function.

#
public void UpdateBag()
    {
        ...
        // Repopulate slots based on the bag items
        foreach (Item item in items)
        {
            GameObject gameObject = Instantiate(inventorySlot, Vector3.zero, Quaternion.identity, contentObject.transform);
            gameObject.GetComponent<Slot>().SetItemSlot(item);
            gameObject.GetComponent<Slot>().SetID((int)count);
            gameObject.name = item.name + " " + count;
            slots.Add(gameObject);

            count += 1f;
        }
        ...
    }
#

instantiating 152 objects is causing the lag 🀦

clever edge
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Swing : MonoBehaviour
{
    public int Debounce;
    private Quaternion OriginalRotation;

    //rotate function
    void rotate()
    {
        OriginalRotation = transform.rotation;

        for(int i = 1; i < 10; i++)
        {
            transform.rotation.Set(0, 0, OriginalRotation.z + (1/i), 0);
            Debug.Log(OriginalRotation.z);

        }
        new WaitForSeconds(Debounce);
        transform.rotation.Set(0, 0, OriginalRotation.z, 0);

    }

    //set the starting rotation
    void Start()
    {
        transform.rotation = new Quaternion(0, 0, -18, 0);
    }

    //rotate when clicked
    void Update()
    {
        if (Input.GetMouseButtonDown(1) == true) {

            rotate();
        }
    }
}

rlly new to cs, why doesnt this work? i just want it to rotate whenever the mouse is clicked

supple citrus
#

Just checking

#

Incase you're left clicking expecting something to happen

clever edge
supple citrus
#

0 is left click

clever edge
#

oh

#

dam lol

potent nymph
#

I have a really long function that I want to reuse, which looks like this

    private void HandleFaceType(int corner1, int corner2, int corner3)
    {
        int count = 0;
        if (vertexData[corner1].isPath) count++;
        if (vertexData[corner2].isPath) count++;
        if (vertexData[corner3].isPath) count++;

//more logic

but the problem is, I want to somehow swap out the condition in the if statements. For example, I'd like to check vertextData[corner].isWater for example

tender wren
#

Change the bool to a function that checks a string?

#

and pass in a string

potent nymph
#

how would that work?

gaunt ice
#

then you need reflection

supple citrus
#

How comes the program doesnt think my mouse pos is inside the rect?

#

The mousepos vector is clearly within range of the TL and BR vertex

tender wren
potent nymph
#

that just returns a boolean

gaunt ice
#

i would do that

[System.Flags]
public enum Terrain{....}
//in your struct or class
public Terrain terrain;//set the flag
//the method
public void Function(...... ,Terrain terrainYouWantToCheck){}
clever edge
#
 private void rotate()
    {
        OriginalRotation = transform.rotation;

        for(int i = 1; i < 10; i++)
        {
            transform.rotation.Set(0, 0, OriginalRotation.z + (1/i), 0);
            new WaitForSeconds(0.1f);

        }
        transform.rotation.Set(0, 0, OriginalRotation.z, 0);

    }

why does this not rotate the object

polar acorn
clever edge
#

how so? its not giving any errors

tender wren
#

I am not familiar with rotating objects, but can you not just modify the transform.rotation itself?

polar acorn
#

Do you know what a quaternion is

potent nymph
clever edge
#

the data that rotation uses

gaunt ice
#

no

polar acorn
clever edge
#

i assumed it's like the rotation you can directly change in unity

polar acorn
#

You really really should not be modifying a Quaternion's individual values unless you have incredibly strong math skills

clever edge
#

is that wrong

polar acorn
#

but it's a quaternion

#

a four dimensional normalized complex number

clever edge
#

how can i not use a quaternion

polar acorn
#

but do you actually have any idea what you're doing

clever edge
#

i am rotating the object along the z axis

polar acorn
#

That's not what that does

#

The X, Y, and Z values of a quaternion have nothing to do with the X, Y, and Z axes of normal euclidian space

#

They're just the first three values of the 4D number that expresses an orientation

clever edge
#

so how do i not use quaternion

unique hull
polar acorn
polar acorn
unique hull
#

Euler angles is also a good choice yeah ^

clever edge
#

lemme see if that works

#
    private void rotate()
    {
        OriginalRotation = transform.rotation;

        for(int i = 1; i < 10; i++)
        {
            transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z + (1/i));
            Debug.Log(transform.rotation.eulerAngles);
            new WaitForSeconds(0.1f);

        }
        transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z);

    }

k so for some reason it's not waiting

#

and it's also not changing the rotation

polar acorn
#

You're still trying to read the Z value of a Quaternion

#

transform.rotation is wizard math do not use any components of it

#

Also your entire loop is pointless because you just instantly overwrite it

clever edge
#

it's an animation

polar acorn
#

no it isn't

#

This entire function runs at once

clever edge
#

what about the for loop?

polar acorn
#

Your new WaitForSeconds does nothing, this isn't a coroutine

#

the loop happens instantly and then is overwritten before the function even ends

clever edge
#

what'll make it wait?

polar acorn
unique hull
#

Googling "Unity documentation - Waitforseconds" gives a great example

summer stump
unique hull
true pasture
#

is there a way I could use the new input system to avoid a fixedupdate. (its not a big deal but helps keep things organized.

polar acorn
true pasture
#

you mean a class variable?

summer stump
#

Yes

true pasture
#

what does that have to do with my question? (ill do it)

frosty hound
#

It's the reason why you're getting the error

true pasture
#

no i know that code is wrong

#

im asking how to avoid having a fixedupdate statement

frosty hound
#

But no, to answer your question, there isn't. The new input system stlil requires you to cache the input and use it in update.

true pasture
#

so theres no way is what youre saying

#

oh

frosty hound
#

Hence the "there isn't"

true pasture
#

my adhd brain skimmed rigyht over that srry

#

but okay thanks

unique hull
#

There isnt sadly , thats why i dont use it tbh

true pasture
#

yeah i mean i can use both systems so ill just use the default system for this

unique hull
#

And i read a few things when i skimmed the web just now , and most of those fixes involves more places, so wouldnt really help your problem πŸ˜›

normal fossil
# clever edge ```cs private void rotate() { OriginalRotation = transform.rotat...
private void Rotate()
{
  StartCoroutine(ChangeRotation());
}

IEnumerator ChangeRotation()
{
  OriginalRotation = transform.rotation;

        for(int i = 1; i < 10; i++)
        {
            transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z + (1/i));
            Debug.Log(transform.rotation.eulerAngles);
            yield return new WaitForSeconds(0.1f);

        }
        transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z);
}

This would wait, however I do not know if the code functions

#

2D world-space FTW

#

Why not just make an animation that loops, do you need to set the rotation programmatically?

clever edge
normal fossil
#

Ah I see, was just wondering

#

But thats how you would use a Coroutine to actually wait. You cant call new WaitForSeconds outside of an IEnumerator

unique hull
#

Just keep in mind that multiple coroutines can overlap , so it might not rotate that much beyond the first 1 second

#

I have a coroutine for reloading for example , but i fix that by having a "Isreloading" bool that just flips on/off for the coroutine

clever edge
normal fossil
#

As I said, I dont know if your code actually worked. I myself am unfamiliar with setting rotations progammatically.

unique hull
#

Quaternions are a bit tricky to use , i could send a snipet of a rotation that works if it would help you?

normal fossil
#

Maybe something like this:

Vector3 originalRotation = this.transform.eulerAngles;
float waitTime = 1f;
for(int i = 0; i < 10; i++)
{
  Vector3 rotationIncrement = new Vector3(0,i,0); //Rotate on the Y axis by one
  transform.eulerAngles = rotationIncrement;
  yield return new WaitForSeconds(waitTime);
}
transform.eulerAngles = originalRotation;```
#

@clever edge

#

should rotate every second then reset.

#

Ill throw it into a new project and test it for ya

vale karma
#

im trying to access a variable from another script. I thought it was NameOfScript.nameOfVariable am I missing something?

clever edge
#

yeah okay i think im just gonna use an animation

#

it would work but im also rotating around the cursor

clever edge
#

(2d project)

vale karma
#

it is

normal fossil
#

Is it in a different namespace?

vale karma
#

basically I made a table you walk up to, a menu is accessable by pressing E as long as your in the trigger. I have the menu popping up when pressing E, but i cant get the variable I set to true from the desk to the script of the player when he presses E

#

ill show code one sec

normal fossil
#

Ok, if the desk is allowing you to open a menu when you're in the trigger, what value are you trying to set. A value on the player?

unique hull
#

Lets get the code first

vale karma
#

public class DeskArea : MonoBehaviour
{

    public bool inRangeOpenMenu = false;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        inRangeOpenMenu = true;
        Debug.Log("Entered Desk Area");
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        inRangeOpenMenu = false;
        Debug.Log("Left Desk Area");
    }

   
}



void OpenRepairMenu()
{
    if(Input.GetKeyDown(KeyCode.E) && repairMenu.activeSelf == false && DeskArea.inRangeOpenMenu == true)
    {
        repairMenu.SetActive(true);
        Debug.Log("Set to true");
    }
    else if (Input.GetKeyDown(KeyCode.E) && repairMenu.activeSelf == true)
    {
        repairMenu.SetActive(false);
        Debug.Log("Set to false");
    }
}
#

the top is the script on the desk, the bottom is a method in the playercontroller script

#
 public BoxCollider2D desk;
 public GameObject repairMenu;
 public GameObject workSpace;
 private Rigidbody2D rb;
 Vector2 move;

 [SerializeField] private float moveSpeed = 5f;
 [SerializeField] private bool isFacingRight = true;

 // Start is called before the first frame update
 void Start()
 {
     rb = GetComponent<Rigidbody2D>();
     desk = GetComponent<BoxCollider2D>();

#

i have this in start but im not too experienced to know what i did exactly lol

normal fossil
#
void OpenRepairMenu()
{
    if(Input.GetKeyDown(KeyCode.E) )
    {
        if(!repairMenu.activeSelf && DeskArea.inRangeOpenMenu)
        {
            repairMenu.SetActive(true);
            Debug.Log("Set to true");
        } 
        else if(repairMenu.activeSelf)
        {
            repairMenu.SetActive(false);
            Debug.Log("Set to false");
        }
    }
    
}```
#

Try this

#

I had a similar issue today with my debug console system, checking comparators in an Input.GetKeyDown was always causing it to return false

vale karma
#

yea its still showing red under DeskArea.inRangeOpenMenu

#

its like it cant see the variable im pointing to

unique hull
#

The original code should work. Its just not as refined as the above one

normal fossil
#

Ohh, are you putting DeskArea class instead of an object?

vale karma
#

yea i dont really have a game object to check, just an ontrigger event to change the value

normal fossil
#

You have to pass it a component, not access it from a class. You could do this:

 public BoxCollider2D desk;

 public DeskArea currentDeskArea;

 public GameObject repairMenu;
 public GameObject workSpace;
 private Rigidbody2D rb;
 Vector2 move;

 [SerializeField] private float moveSpeed = 5f;
 [SerializeField] private bool isFacingRight = true;```
vale karma
#

i dont wanna use the value right away, but when i hit a key, so thats why its not just on triggerenter

normal fossil
#

and then set the currentDeskArea when the player enters the trigger.

vale karma
#

okay ill try it

normal fossil
#

and change DeskArea to currentDeskArea like this:

void OpenRepairMenu()
{
    if(Input.GetKeyDown(KeyCode.E) )
    {
        if(!repairMenu.activeSelf && currentDeskArea.inRangeOpenMenu)
        {
            repairMenu.SetActive(true);
            Debug.Log("Set to true");
        } 
        else if(repairMenu.activeSelf)
        {
            repairMenu.SetActive(false);
            Debug.Log("Set to false");
        }
    }
    
}```
#

and in the Desk script do this:

vale karma
#

ohhh okay, yea thats what i had wrong i think, i had workSpace as a public DeskArea, i think i had code wrong so i chagned it to GameObject, ima check if it worked rq

normal fossil
#
private void OnTriggerEnter2D(Collider2D collision)
    {
        //Add a check to make sure its the player
        inRangeOpenMenu = true;
        collision.gameObject.GetComponent<PlayerController>().currentDeskArea = this;
        Debug.Log("Entered Desk Area");
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        inRangeOpenMenu = false;
        collision.gameObject.GetComponent<PlayerController>().currentDeskArea = null;
        Debug.Log("Left Desk Area");
    }```
#

I think setting it to this would work however I am also a newbie

#

also if your script is not called PlayerController you have to change that in the GetComponent to the name of the class (ex. if your player controller script is named PlayerMovement, then change it to that)

vale karma
#

woahh it worksss!

normal fossil
#

😁

vale karma
#

and im not too sure what you mean by this code ^^ i do know i did it kind of a jank way tho, im much newer than you XD

normal fossil
#

No youre good your learning I was doing the same thing 6 months ago, and I've been trying to make games since I was 12

vale karma
#

Yea im stuck in the last half of tutorial hell, ive been really grinding to try and branch out into something i like

unique hull
normal fossil
#

You could just set the script to reference that one desk, however, if you have multiple desks the playerController wont know which one is the current desk, and if you have functionality for each desk it would cause issues. In its current state its unneeded

#

Thanks πŸ˜›

vale karma
#

rn im making a Computer repair shop, i work at one, so i can really create a niche game with good detail, but as you can prolly tell I have a scope too large for my brain

normal fossil
#

Me too I am trying to create perlin noise terrain generation

#

its insanely difficult Lmao

vale karma
#

and yea for now I will be making static levels, I only need a few desks to put laptops or desktops on, soo.. im in way over my head XD

normal fossil
#

I have a simple generator but without tilemap rules its garbage

#

And yeah, that's good man. You'll get there.

#

What I got stuck on early on, was Inventory systems. Learn about arrays and lists, it will greatly help you in the future.

vale karma
#

how long does it usually take to learn anything past movement XD it seems like I know what game mechanic i want to implement but not what to look or search for

#

I always end up making movement on a character, then thinking of something else to add, by the time i go to add it its too complicated and i give up

vapid spire
#

can someone help me to get a sound to be toggle-able

#

ill send the code for someone to correct

#

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

public class BathromSink : MonoBehaviour
{
public GameObject openText;

public AudioSource sinkSound;


private bool inReach;




void Start()
{
    inReach = false;
    sinkSound.enabled = false;
}

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Reach")
    {
        inReach = true;
        openText.SetActive(true);
    }
}

void OnTriggerExit(Collider other)
{
    if (other.gameObject.tag == "Reach")
    {
        inReach = false;
        openText.SetActive(false);
        Debug.Log("IsInReach");
    }
}





void Update()
{

    if (inReach && Input.GetButtonDown("Interact"))
    {
        sinkSound.enabled = true;
        sinkSound.Play();
    }


}
public void StopSink(AudioSource sinkSound)
{
    if (inReach && sinkSound.enabled == true && Input.GetButtonDown("Interact"))
    {
        sinkSound.Stop();
        sinkSound.enabled = false;
    }
}

}

normal fossil
#

Giving up, made me stop working on a game that me and my friend were making for years. Made me stop working on my current project 2 years ago, and it destroys any hope of a future making games. You cant give up. If you get stuck take a break. Clear your head and then try to approach from a different angle. If you're trying to add an inventory system. Make it super simple at first. Just make a list. Make it so it only contains words

List<string> items = new List<string>();```

Make it simpler for you to understand
vale karma
#

you can add a toggle from the UI gameObject. Then set that toggle to the audio, set the audio to the component

normal fossil
#

I frequently ask ChatGPT to explain things too, especially certain parts of a problem. Also have a plan and dedicate a certain amount of time

vapid spire
#

it is a sink you interact with

vale karma
#

i learned some windows forms using VB so i know a lil about arrays and lists

normal fossil
#

You got it man, YouTube unity tutorials can be bad if you don't try to understand what you're writing beforehand.

vale karma
#

theyre the worst clickbait haha, it starts as "download unity" to "im just gonna skip ahead coding a flying car rq"

#

im on the learn.unity site

normal fossil
#

Yeah thats a good place to understand stuff. I learned how to use Tilemap rulesets on there

vale karma
#

ive dabbled, are you talking about making tilesets easier to paint?

normal fossil
#

Yes, making it so tiles with certain conditions, like bounds or corners, is automatic

vale karma
#

I saw a vid on that and was super excited to try that next time i want to get into top down games. That looked so much better than wat i did. I quit making top downs bc of that

normal fossil
#

Yeah manually drawing tiles can be ridiculous. Its easier for modifying game worlds realtime if youre making a survival game like me.

vale karma
#

you have any builds made?

normal fossil
#

Yeah, me and my friend have been making the game for the past 2 months

#

I'll dm you a Steam Key

vale karma
#

oh crap its demoed πŸ˜„ does it cost anything to list on steam?

normal fossil
#

Yeah, $100 bucks

#

USD

#

But, you get it back once you make $1000

vale karma
#

I dont know how successful single dev games are, Id be happy with 5 bucks

normal fossil
#

Hey, Ive made 5 grand off a really bad game I made Lol

#

Farstorm on Steam

#

thats before taxes and before steam taking their cut but still was decent

#

also over the course of a year and a half

#

Honestly people did enjoy it somehow so it worked out πŸ˜›

#

Mostly laughed at it

vale karma
#

haha that game is cool man, I love the nintendo look. does it not have any controls but E? XD

normal fossil
#

E: Opens Menu R: Opens Bag T: Opens Crafting, press c or click current item to set an item, pressing b allows you to build, left click builds an object, right click stops building

vale karma
#

The menu looks nice

normal fossil
#

Thanks

#

Also some funny debug test items in there so if you see anything like that ignore it Lol

vale karma
#

oh crap theres much more than i thought haha

normal fossil
#

Yeah, since there is no indicators it looks empty Lol

#

Save and Load system, crafting, inventory, building, chopping trees, picking up items

#

Oh, press Space to interact with objects

#

Day and night system, weather system

#

Theres a lot getting put into it

#

R rotates buildable items too

vale karma
#

jesus lol yea you may need a good UI or tutorial for that one, theres alot in there, the tree system is dope

#

it acts just like my desks

normal fossil
#

Yes, but instead of using a Trigger, it uses Raycasts

vale karma
#

does that work on a more managable scale than trigger? if i add another desk i feel like im gonna have to duplicate alot of code

#

oh god i suck with prefabs

normal fossil
#

I wanted to make it so objects have to be looked at by the player in order to be interacted with, and, I find it easier for tilemap grid based movement

#

Heres a video of the farming system

vale karma
#

jesus that only took 2 months?

normal fossil
#

And a lot of failed attempts over 6 years Lol

vale karma
#

i dont think ive put out a finished game yet. Ive been working on Unity for about half a year now

normal fossil
#

Make something stupidly simple a cookie clicker game and force yourself to finish it. Making games is the best way to learn

vale karma
#

im too off an on to say half a year,but this month or so ive been on everyday

normal fossil
#

Yeah, having a project youre invested in makes it a lot easier to work on it every day

#

The games not done, and is going through lots of changes as we make design decisions but I'm gonna add you if you need help just send me a DM if im online I'll help you out

#

Gonna head off for the night good luck on your journey bro

vale karma
#

sounds good, thanks for the help

normal fossil
#

np

lavish terrace
#

how to add a source to a position constraint using codes

dusty coral
#

why is it not autocompleting?

lavish terrace
#
{
    public Transform playerPos;
    public PositionConstraint positionConstraint;

    void Start()
    {
        positionConstraint = this.gameObject.GetComponent<PositionConstraint>();
        playerPos = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();

        this.gameObject.transform.position = playerPos.position;

        positionConstraint.AddSource();
    }
}
charred spoke
lavish terrace
#

what goes next?

charred spoke
#

AddSource take a parameter

#

You cant just call it like that

lavish terrace
charred spoke
#

Well I am on my phone but the code will look something like var source = new ConstraintSource { sourceTransform = theTransformYouWant, weight = theaweightYouWant};

proud sundial
#

hey guys, it's been a while since i posted here
so i'm making a game where you shoot at machines to make them pull you in or push you out, but the intensity of the pull/push is largely inconsistent and depends on a variety of factors like how close you are to the center of the machine.
i want the machines to always launch you with the same speed. how can i go about doing this? at the moment i am using AddForce to boost the player in/away from the direction they shoot at the machine in. is there another way to reliably push the player around?

eternal needle
#

you also likely want that force to be an Impulse. Id also ensure that its not applying more than once

native seal
#

Anyone know why I can see the skybox through my tiles using pixel perfect cmaera?

proud sundial
#

you're right about the velocity thing, i wonder if there's a way i cna make that not affect the push/pull

charred spoke
#

If you trully want thee exact same force from the push pull objects then zero the player velocity before applying the force however that may be undesirable. I for one always try to perserve player velocity

proud sundial
#

i'll see how it works out

wintry quarry
#

I.e. void

hot sky
solemn bobcat
# native seal Anyone know why I can see the skybox through my tiles using pixel perfect cmaera...

It's a common problem. My bet is that due to floating point precision sometimes it takes wrong pixels on the edge of tiles and takes a pixel that is out of bounds. There are a few workarounds to fix it. Some are listed here:
https://blog.terresquall.com/2023/03/how-to-fix-gaps-in-your-tiles-in-unitys-2d-tilemaps/
I think Sprite Atlas should work the best. If you want alternative solutions, you can configure your tiles to slightly overlap with each other (should work fine as long you don't use transparency) or you can draw extra pixels on the edges of your tiles (e.g. if your tiles are 16x16 pixels, you can draw them 18x18 pixels in the texture).

gusty gyro
#

how do it? nvm got it, thanks!

kindred halo
#

oh so you mean I get the Cross direction from the wall and tell my player to go in that direction?

earnest tendon
#

Hello, so im working on a Vampire survivors type game and yesterday i accidently fucked up the code and cant find where it is and now the player aint even loosing HP and the stats aint showing up in the pause menu, plus im getting all of these errors, ive tried to find where the errors are through what its telling me but i cant figure out where the errors are coming from

#

everything else ive done so far works, except for the HP bar for some reason

#

the player also takes constant damage even tho i set it so the player takes damage every 0.5 seconds

#

but it just refuses to work

hot sky
#

Go into whatever object has the EnemyStats script and set the public variables on the script to whatever they should be. It looks like you accidentally unset all the public variables on the script and now the damage interval has defaulted to 0 and the GameObject variables are null.

earnest tendon
#

so the issue is on the enemy stats script?

#

everything is public there

timber tide
#

where's your scene at or are you loading most of it in

hot sky
#

I think

timber tide
#

also do a paste site cause posting code like that sucks in discord

#

!code

eternal falconBOT
earnest tendon
#

i tried

#

its just way to big to be posted like that

timber tide
#

refer to links

earnest tendon
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyStats : MonoBehaviour
{
    public EnemyScriptableObject enemyData;

    //Current stats
    [HideInInspector]
    public float currentMoveSpeed;
    [HideInInspector]
    public float currentHealth;
    [HideInInspector]
    public float currentDamage;

    public float despawnDistance = 20f;
    Transform player;

    void Awake()
    {
        //Assign the vaiables
        currentMoveSpeed = enemyData.MoveSpeed;
        currentHealth = enemyData.MaxHealth;
        currentDamage = enemyData.Damage;
    }

    void Start()
    {
        player = FindObjectOfType<PlayerStats>().transform;
    }

    void Update()
    {
        if (Vector2.Distance(transform.position, player.position) >= despawnDistance)
        {
            ReturnEnemy();
        }
    }

    public void TakeDamage(float dmg)
    {
        currentHealth -= dmg;

        if (currentHealth <= 0)
        {
            Kill();
        }
    }

    public void Kill()
    {
        Destroy(gameObject);
    }


    void OnCollisionStay2D(Collision2D col)
    {
        //Reference the script from the collided collider and deal damage using TakeDamage()
        if (col.gameObject.CompareTag("Player"))
        {
            PlayerStats player = col.gameObject.GetComponent<PlayerStats>();
            player.TakeDamage(currentDamage);    //Make sure to use currentDamage instead of weaponData.Damage in case any damage multipliers in the future
        }
    }

    private void OnDestroy()
    {
        EnemySpawner es = FindObjectOfType<EnemySpawner>();
        es.OnEnemyKilled();
    }

    void ReturnEnemy()
    {
        EnemySpawner es = FindObjectOfType<EnemySpawner>();
        transform.position = player.position + es.relativeSpawnPoints[Random.Range(0, es.relativeSpawnPoints.Count)].position;
    }
}

checked the inspector and nothing seems wrong, the values are as i set them, heres the enemystat script

#

everything seems to be right on all scripts so i got no idea why the fuck im getting these errors

timber tide
#

well, hard to help since I can't tell you what's happening on line 70

#

because posting in discord doesn't apply that

earnest tendon
#

oof

ivory bobcat
earnest tendon
#

should be whats inside the Awake function

timber tide
#

but if the inspector stuff is set, then you should debug where you're doing GetComponent and make sure it's being set

#

bad weather today huh

ivory bobcat
earnest tendon
#

hold up im putting the code in a hastebin

#

ok so thats the EnemyStats script

ivory bobcat
#

I'm assuming it's this line player.TakeDamage(currentDamage);

earnest tendon
#

nope

timber tide
#
        EnemySpawner es = FindObjectOfType<EnemySpawner>();

Log it and make sure it's not null

ivory bobcat
#

Ah nvm
es.OnEnemyKilled();

timber tide
#

if it is then it's not finding it

earnest tendon
timber tide
#

As I was asking where's the rest of your scene

#

lol

ivory bobcat
#

Maybe reference the spawner instead of searching for it, if possible.

earnest tendon
#

like the inspector stuff?

ivory bobcat
#

Finding doesn't guarantee that it's valid

timber tide
#

Unless you've everything contained on the Scene Container object there

hot sky
#

Maybe this should be a thread

earnest tendon
#

maybe

ivory bobcat
timber tide
#

Anyway, yeah using find is terrible. If you don't want to set references, then consider looking into a singleton pattern and grabbing references for spawn like the Enemy Spawner

earnest tendon
#

i think im using singletons somewhere

gusty gyro
#

does attaching a new child object will pause the animation? because its happening to me right now

earnest tendon
timber tide
earnest tendon
#

8-Bit vampire survivors issues

lunar grove
#

I'm having an issue with color.lerp, it won't change smoothly with a transition as I expected, it only changes color once then after a few seconds it instantly changes color.

 IEnumerator DayToNight()
    {
        float time = 0;
        float transitionTime = 2;
        while(time < transitionTime)
        {
            mainCamera.backgroundColor = Color.Lerp(new Color(214, 214, 214, 0), new Color(0, 0, 0, 0), time / transitionTime);
            time += Time.deltaTime;
            yield return null;
        }

        mainCamera.backgroundColor = new Color(0, 0, 0, 0);
    }

Here's my code

ivory bobcat
lunar grove
#

like this

#

I'm trying to change it from one color to another

#

color a to color b

#

within a duration

ivory bobcat
lunar grove
lunar grove
ivory bobcat
#

I'm guessing alpha zero isn't what you're wanting.

#

What are you actually getting?

lunar grove
#

its a solid color

#

I just want to make a smooth color transition from color a to color b

ivory bobcat
#

If you want values up to 255, use Color32

lunar grove
#

so I shouldn't use color with rgb then?

ivory bobcat
lunar grove
ivory bobcat
#

I don't know what you're doing but 0 alpha would make the color transparent - invisible.

kindred halo
#

Can anyone tell me how can I get the cross out of an layermask object?

lunar grove
#

oh wait its color32

#

ok it works

lunar grove
eternal needle
lunar grove
#

I feel bad for literally giving me the right code to this though

#

Might as well get something to learn from this

ivory bobcat
gusty gyro
#

Help, im planning to do the second image but it does this

The code: (GrabbedObject is the Red Object)

grabbedObject.GetComponent<Rigidbody2D>().isKinematic = true;
grabbedObject.transform.position = ray.position;
grabbedObject.transform.SetParent(transform);
kindred halo
eternal needle
lunar grove
ivory bobcat
# lunar grove meaning?

Normalized values are within ranges of [0f, 1f] whereas Color32 accepts values from [0, 255]

kindred halo
ivory bobcat
lunar grove
eternal needle
ivory bobcat
lunar grove
ivory bobcat
#

Going from no color white to no color black would just have you see a no color.

barren vapor
#

maybe it attaches to the pivot

ivory bobcat
#

Basically, you were using non normalized values for Color that was expecting normalized values and you had alpha transparency set to max which made your color invisible to the eye.

gusty gyro
lunar grove
barren vapor
gusty gyro
barren vapor
kindred halo
ivory bobcat
#

Assigning it the cross product of two Vectors make little sense.

kindred halo
#

I wasn't assigning
I was trying to show what I'm trying to get

wet heath
#

reload scene on player death issues

ivory bobcat
kindred halo
ivory bobcat
#

What does a Vector3 have to do with a layermask?

kindred halo
#

nothing

worthy veldt
#

i just find out that dictionary cannot have multiple key for a value (GameObject), i thought only the key that has to be unique.

#

what collection should i use for that purpose ?

ivory bobcat
worthy veldt
#

wait

timber tide
#

you can do composite keys

#

and tuples

ivory bobcat
worthy veldt
#

i got the error message that states it

ivory bobcat
#

Perhaps show us this error message?

worthy veldt
#

multiple value detected or something

#

sec im looking fo rit

#

i already changed my code

timber tide
#

yeah, only the key is what needs to be unique

worthy veldt
#

yea i missread.. so my problem lies elsewhere then ArgumentException: An item with the same key has already been added

ivory bobcat
#

Yeah, it would seem to be a duplicate property or something

lunar grove
#

Hello, I tried to make an infinite loop coroutine to make gameobject no visible until a certain condition is met

    IEnumerator HideDayBackground(ObstacleScript[] gameObstacles)
    {
        while(true)
        {
            foreach (var gameObstacle in gameObstacles)
            {
                if (gameObstacle.prefabObjectType == PrefabObjectType.Day)
                {
                    gameObstacle.gameObject.SetActive(false);
                }
                else if (gameObstacle.prefabObjectType == PrefabObjectType.Night)
                {
                    gameObstacle.gameObject.SetActive(true);
                }
            }
        }
    }

It however crashed my unity editor lol

gaunt ice
#

freeze is not crash

#

you have a dead loop then ofc it freezes your editor

quaint flicker
#

I've put a character controller on my enemies. I have some code to make them face the player and Move() towards them. I implemented collisions with some throwables and the player with OnControllerColliderHit and sure enough they wouldn't react to stuff thrown at them when they're in idle state. (because the oncontrollercolliderhit is only called whenever the controller is moving). So beginner question: how do I setup my enemies? the character controller ensured they would follow slopes and the ground correctly. I was hoping to make them use navmeshes eventually. But if I want them to be able to fall off a cliff or something I still need to just put a capsule collider on them and implement things I got from the character controller myself? What's the "standard" way of doing this?

timber tide
#

if you want physics with navmesh you simply don't compute the path when they aren't grounded

#

nor allow them to continue moving on the path they were currently on

exotic hazel
#

how do i find the coordinates of where the player is looking at

gaunt ice
#

raycast a screen ray and get the hit.point

#

probably start from the middle of screen space

vast vessel
#

Is it better to use Array.Find or to loop through the arrays items and find the item im looking for?

gaunt ice
#

use dictionary

vast vessel
#

Thats not an answer to my question

timber tide
#

array is pretty simplified concept itself so there's no real pattern matching beyond iterating and comparing it yourself

gaunt ice
#

btw i would avoid using callback, that is much slower then normal function call (though callback is much easier to use)
and i will use dictionary or sorted set if possible

#

O(n)=O(10n) when n->infinity

rare basin
#

that is a code relating channel, not off-topic

ebon robin
#

How do we add depth to Unity 2D? (like jumps and stuffs)
I am making a top-down game

queen adder
lost hamlet
rare basin
scarlet skiff
#

would this not return true if the player is falling? (or whatever i run this on is moving downwards)

kindred halo
#

Do you guys think this is the right way to do this?
basically I'm moving forward When I press W

lost hamlet
rare basin
ebon robin
#

I am thinking of adding z_value into consideration, making the y_value that appears on the screen = y_grounded_value + some_coefficient*z_value

#

how do we implement this? can we change unity rendering code?

scarlet skiff
#

can you guys elaborate

rare basin
#

it returns a value of your joystick/keyboard input

#

down = -1

#

no input = 0

#

up = 1

#

Since input is not smoothed, keyboard input will always be either -1, 0 or 1

scarlet skiff
#

so its NOT if the player is falling, but if i press the down arrow button?

rare basin
#

how is that related to the player "falling"

#

this is just a input detection

scarlet skiff
#

moving down in the y axis

rare basin
#

you need to make your own falling logic

#

it's just input

#

it doesnt detect if player is moving down in the y axis

#

it detects if you press "S" key or left stick on gamepad down, or dpad down or whatever

scarlet skiff
#

ok ty

#

would these work?

#

lastPosition = playerTransform.position;

in update

burnt vapor
scarlet skiff
#

it didnt

#

😭

#

seems that it never returns true

burnt vapor
#

Also for the sake of improving the way you write code, you can just do return lastPosition.y < playerTransform.position.y

scarlet skiff
#

even if the player moves up or down

burnt vapor
#

You can use Debug.Log for that and then look at the editor console for the output

#
Debug.Log($"{lastPosition.y} - {playerTransform.position.y}");

Something like this, in your Update method.

scarlet skiff
burnt vapor
#

Yes

#

I would guess lastPosition is updated wrong and will not compare correctly

scarlet skiff
#

ok so it seems they are always the same

#

even when i jump

burnt vapor
#

Yes so my guess is you update lastPosition, and then check against the current position

bronze yacht
#

Hey Guys
Does somebody know if the Object reference changed or something in the newer version?'Object' is an ambiguous reference between 'UnityEngine.Object' and 'object'

burnt vapor
#

You need to make sure you update it after. One way would be to use LateUpdate

#

But I do advice against it

bronze yacht
burnt vapor
#

Or add this:
using object = UnityEngine.Object;
If you need the namespace.

scarlet skiff
burnt vapor
#

So you don't update it immediatley, but instead you use something like a Queue for example

bronze yacht
burnt vapor
#

All in all I just don't advice LateUpdate since you either use the normal variant or a late variant, and if you still need to have something happen later then you have no proper solution

#

So uhh, probably better to have a Queue and to take the second entry. The first one would be the same again most likely

scarlet skiff
#

okay so there a few problems, mainly that it somehow can set jump to true even when the player is idle, imma take a look at queue and see how it works, cuz rn i udpate the pos last thing in update

burnt vapor
#

If you use the Queue class it works similar to a List, but instead of adding items you enqueue items. If you set the max size to 2 it will pop whatever items are added first so you can just get the second entry every time

#

Probably not very efficient though, but I think a queue is pretty solid when it comes to tackling the issue before you do any sort of polishing.

#

Be sure to make a GetLastPosition method or property that gets the entry in the queue for you to avoid having to rewrite a lot of code later

onyx tulip
#

When i run left my character has a greater hitbox than when i walk right

#

any way to help?

exotic hazel
#

maybe the colliders?

#

did u check them

onyx tulip
sly magnet
#

I've been following a guide until I ran into a code i wasn't familiar with, it was called BoxGroup, what is it used for and is it code used from the asset store?

burnt vapor
#

Not much that can be said here unless you share the guide, perhaps

lunar grove
#

is there a way to check if a specific GameObject exists?

burnt vapor
lunar grove
burnt vapor
#

Yes, but why? Why check for a gameobject? What is the purpose of the script?

#

I doubt you are checking a random gameobject unless you aim for a specific system

lunar grove
burnt vapor
#

Again, what is this system? Please specify it

#

Is it a monster spawner? Please share the code

lunar grove
#

It's actually just the chrome dino game lmaoo in unity, I need the moon phases

#

once a previous moon phase has gone by the next one must progress

burnt vapor
#

Why not reuse the same moon instance and change its sprite to the next phase?

#

I feel like that's easier than removing the last moon instance every time

lunar grove
burnt vapor
#

Either way, if you were to spawn a new gameobject then consider using an enum, and a variable that holds that enum as the "last phase"

#

Then when you spawn the next one, check this variable for the next enum to spawn

#

And you can contain the moon's gameobject in another variable so you know what to destroy

burnt vapor
lunar grove
onyx tulip
#

@burnt vapor

onyx tulip
short hazel
#

What does it say?

dark elbow
short hazel
#

Yeah, your variable must be of type SpriteRenderer

#

Image doesn't have that

burnt vapor
dark elbow
#

@short hazel i still have the error evne by switching it to SpriteRenderer

short hazel
#

Show the component in the Inspector

#

The one you're trying to reference

dark elbow
#

u mean the health bar?

short hazel
#

Whatever you're trying to modify the fill amount of

dark elbow
burnt vapor
# dark elbow

What is Image here? I think your mistake is not using UnityEngine.UI.Image

#

Because that one has fillAmount

short hazel
#

Yeah so that's the Image type

burnt vapor
#

Could be wrong tho

#

Newer Unity versions have some changes with UI so you might be using a different Image class

short hazel
#

So if your code fails to find a fillAmount property on it, then it's not finding the right Image type - did you make your own class Image? It's picking that one first

dark elbow
burnt vapor
#

But you have a separate package for UnityEngine.UIElements.Image.fillFormat you need to install or something

rare basin
short hazel
# dark elbow yes

Well there you go. Avoid naming your own classes the same as Unity's

#

Since your classes are put in the global namespace, it's technically closer to the one in UnityEngine.UI

#

So the compiler takes yours first

dark elbow
#

it still doesent work

#

i still get the same error

short hazel
#

Did you rename your own Image class to something else?

dark elbow
#

yes

short hazel
#

Make sure you saved and returned to Unity so the code is recompiled

#

Clear the console and make sure the error is not present there

dark elbow
#

still nothing

short hazel
#

Show the declaration of your variable

dark elbow
short hazel
#

Okay Ctrl+Click that Image and see where it takes you

dark elbow
#

It takes me to Image.cs

short hazel
#

Which one? Unity's

rare basin
#

did you also changed your filename

#

from your old Image class

#

show the console

dark elbow
#

yes, unity's

short hazel
#

Post a screenshot of it

#

The first few lines of code

rare basin
#

you can just hover over the Image variable type and see in which namespace it is

dark elbow
short hazel
#

No that's not Unity's

#

That's Microsoft.Unity.VisualStudio

dark elbow
#

oh

short hazel
#

You have the wrong using directive in your own code

#

Unity's Image class is in UnityEngine.UI

dark elbow
#

its fixed now

#

thank you

graceful basin
#

im trying to make my exp collectible spawn after destroying, but debug log is not showing "Exp collectible spawned". where the problem could be?

eager elm
frosty blaze
#

I have an audio listener and audio source, now I need to increase the speed of sound so how do I do it?
my current part of code:

        {
            score++;
            speed+=0.2f;
            Debug.Log("Score: " + score);
            //transform.localScale += new Vector3(0.2f, 0.2f, 0f);
            //GameObject.FindWithTag("Food").audioSource.Play();
            SpawnRandom("Food");
            //SpawnRandom("MWall");
        }```
frosty blaze
eager elm
eager elm
rare basin
rare basin
frosty blaze
#

so += right?

keen hill
#

can someone help me with the fix?

rare basin
frosty blaze
#

then?

scarlet tiger
graceful basin
scarlet tiger
#

do what you want with that array

keen hill
#

so it cant be in an if

eager elm
#

a pitch of 2 makes the sound play twice as fast as with a pitch of 1

graceful basin
scarlet tiger
rare basin
#

but in reality you are not increasing the actual audio clip speed

scarlet tiger
#

you could see if the length is greater than 0, or loop through the array

#

depends on what you are trying to do

keen hill
#

what lenght?

rare basin
#

you can use pitch scaling

#

to imitate that

eager elm
# frosty blaze then?

just try it out and see if it is what you want, pitch of 1 is usually the default value and 3 is max

frosty blaze
#

oh

rare basin
#

time stretching requires a more complex algorithm that can be quite slow

keen hill
#

i was trying to check whenever something collides i can do something like pickit up

#

for example

scarlet tiger
#

ok, so i'd just loop through the array and do your pick up logic

rare basin
#

you can modify the pitch, then do 1/pitch in the audio mixer

#

only way to imitate the "speed up"

#

just changing the pitch wont do the trick

keen hill
#

how can i loop tho sorry im new to this stuff

rare basin
#

your audio clip will sound very high pitched only, not speeded up (it will be played in the same duration, just higher pitched)

eager elm
graceful basin
scarlet tiger
#

like what an array is and looping

#

those are key concepts

eager elm
keen hill
#

probably would be neccessary but its boring tho

rare basin
keen hill
#

and coding seems more fun even when im struggling

timber tide
#

good luck getting far without it

rare basin
#

if you dont understand it

keen hill
#

okay thanks :3

graceful basin
cosmic dagger
eager elm
strange granite
#

what can i do?

short hazel
#

Remove line 2. That's causing the ambiguity because both namespaces have a MinAttribute in them, so the compiler can't choose for you

graceful basin
dim halo
#

hey guys, can someone tell me why I cant move in the scene view in unity 3d?

#

I'd appreciate any kind of help

buoyant knot
#

you aren’t really putiting input into the game while in scene view

#

you can only really move things via transforms etc, like you would do in editor

ionic lava
#

Can anyone help me to fix an issue regarding Attack animation?
I have a PlayerObject with a Combat script. In this script I create a method "public IEnumerate DamageWhileAnimationPlays()"
on my PlayerObject I have a SubObject which is the PlayerSprite with an Animator attached. When I now try to create an animation Event and call the "DamageWhileAnimationPlays()" it doesnt show me any methods within the "create animation event" -window I know it's probably because the Combat Script is attached to "Player" and the Animator is attached to "Player/PlayerSprite". But is there a way to get this working?

ionic lava
#

using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Timeline;

public class PlayerCombat : MonoBehaviour
{
    public Animator _anim; 
    private RaycastHit2D[] hits; 
    private float _attackTimeCounter;

    [SerializeField] private Transform _attackPoint;
    [SerializeField] private LayerMask _attackableLayer;
    [SerializeField] private float _attackRange = 0.8f;
    [SerializeField] private float _attackDamage = 1f; 

    [SerializeField] private float _timeBetweenAttacks = 0.15f;

    public bool _shouldBeDamaging { get; private set; } = false; 
    
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    private void Update()
    {
        if (_attackTimeCounter >= _timeBetweenAttacks && (Input.GetButtonDown("Fire1")))
        {
            _anim.SetTrigger("Attack");
        }

        _attackTimeCounter += Time.deltaTime;
    }
    public IEnumerator DamageWhileSlashIsActive()
    {
        _shouldBeDamaging = true; 

        while(_shouldBeDamaging)
        {
            hits = Physics2D.CircleCastAll(_attackPoint.position, _attackRange, transform.right, 0f, _attackableLayer); 

            for(int i = 0; i < hits.Length; i++)
            {
                IDamageable iDamageable = hits[i].collider.gameObject.GetComponent<IDamageable>();
                //if we found an iDamageable
                if (iDamageable != null)
                {
                    //apply damage
                    iDamageable.Damage(_attackDamage);
                }
            } 

            yield return null; 
        }  
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireSphere(_attackPoint.position,  _attackRange);
    }
    
    #region AnimationTriggers

    public void _shouldBeDamagingToTrue()
    {
        _shouldBeDamaging = true; 
    }

    public void _shouldBeDamagingToFalse()
    {
        _shouldBeDamaging = false; 
    }

    #endregion 
}
#

I got this script attached to the Object "Player" and got the Animator on the Object "Player/PlayerSprite". And basically I want to create an Animation Event with DamageWhileSlashIsActive() and one with _shouldBeDamagingToFalse()

dim halo
#

can someone tell me why the object isnt moving in the game?

#

I'd appreciate any kind of help

timber tide
eternal falconBOT
thorn holly
dim halo
thorn holly
rich adder
#

screenshots are a pain in the ass to view, esp on mobile

ionic lava
thorn holly
dim halo
#

there it is

#

@rich adder

#

can you help me out

thorn holly
#

So make a public GameObject player; and in the inspector, drag the player into variable. Then, just say player.GetComponent<PlayerCombat>().theMethodIWantToReference @ionic lava

rich adder
dim halo
#

0 errors

ionic lava
#

Ohhh I see. I'll give it a try. Thanks! @thorn holly

dim halo
#

no issues found

rich adder
thorn holly
dim halo
thorn holly
dim halo
#

yes

rich adder
# dim halo

the inspector, show it on the object inspector

#

this shows nothing

dim halo
#

it works

rich adder
#

oh alr then

#

this can be simplified with GetAxis btw

safe barn
#

In this code

public float speed = 1f;
    public float startAngle, endAngle;
    private float startRot, stopRot, lerpAlpha, currentRot;
    private bool animate, isRotated;

    void Update()
    {
        if (Input.GetKey(KeyCode.Z ) || Input.GetKey(KeyCode.X)) 
        {
            if (!animate)
            {
                animate = true;
                startRot = isRotated ? startAngle : endAngle;
                stopRot = isRotated ? endAngle : startAngle;
                currentRot = startRot;
            } 
        }

        Rotate(); 
    }

    private void Rotate()
    {
        if (!animate) return;

        currentRot = Mathf.Lerp(currentRot, stopRot, Time.deltaTime * speed);
        transform.rotation = Quaternion.Euler(Vector3.back * currentRot);

        if (Mathf.Abs(currentRot - stopRot) <= 0.1f)
        {
            animate = false;
            isRotated = !isRotated;
        }
    }

When Z or X is pressed the object rotates towards a different place, but the code works overall and the object rotates. But what im trying to say is that its not supposed to rotate the either way (its hard to explain, i recorded it)

#

ITs not supposed to rotate to the left

dark oak
#

guys how do i start 2d indie game development?

rich adder
dark oak
timber tide
safe barn
#

The pivot point ( the back of the bed) rotates on the Z axis

#

which is up and down

rich adder
scarlet hull
#
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class turret : MonoBehaviour
{ 
    [SerializeField] private Transform GunRotation;
    [SerializeField] private float Range = 3f;
    private Transform target;
    [SerializeField] private LayerMask enemyMask;

    void Start()
    {

    }

    void Update()
    {
        if (target == null)
        {
            FindTarget();
            return;
        }

        RotateTowardsTarget();
    }

    private void OnDrawGizmosSelected()
    {
        Handles.color = Color.black;
        Handles.DrawWireDisc(transform.position, transform.forward, Range);
    }

    private void FindTarget()
    {
        RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, Range, Vector2.zero, 0f, enemyMask);
        if (hits.Length > 0)
        {
            target = hits[0].transform;
        }
    }

    private void RotateTowardsTarget()
    {
        float angle = Mathf.Atan2((float)(target.position.y - transform.position.y), (float)(target.position.x - transform.position.x)) * Mathf.Rad2Deg;
        Quaternion targetRotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
        transform.rotation = targetRotation;
    }
}```
eternal falconBOT
rich adder
#

Large code, use links

scarlet hull
ionic lava
thorn holly
#

Fs!

timber tide
thorn holly
#

Is there a way to make certain methods in a delegate run before others? Or is it all at the same time when the delegate is called.

scarlet hull
#

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

public class turret : MonoBehaviour
{ 
    [SerializeField] private Transform GunRotation;
    [SerializeField] private float Range = 3f;
    private Transform target;
    [SerializeField] private LayerMask enemyMask;

    void Start()
    {

    }

    void Update()
    {
        if (target == null)
        {
            FindTarget();
            return;
        }

        RotateTowardsTarget();
    }

    private void OnDrawGizmosSelected()
    {
        Handles.color = Color.black;
        Handles.DrawWireDisc(transform.position, transform.forward, Range);
    }

    private void FindTarget()
    {
        RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, Range, Vector2.zero, 0f, enemyMask);
        if (hits.Length > 0)
        {
            target = hits[0].transform;
        }
    }

    private void RotateTowardsTarget()
    {
        float angle = Mathf.Atan2((float)(target.position.y - transform.position.y), (float)(target.position.x - transform.position.x)) * Mathf.Rad2Deg;
        Quaternion targetRotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
        transform.rotation = targetRotation;
    }
}```
rich adder
#

I been said use Link for large code

eternal falconBOT
scarlet hull
#

this

rich adder
native flicker
#

just me or did he sent wrong script

rich adder
#

its complaining about movement

#

you sent turret

scarlet hull
#

oohh

rare basin
#

why are all of your classes starting from lower case?

#

that's not good C# and Unity standard

dim halo
#

guys am I supposed to add f next to the numbers in the vector

scarlet hull
dim halo
#

for instance instead of (0,5,0), should I write (0,5f,0)

vale karma
#

if theyre floats yes

safe barn
#

you put f after the number

polar acorn
safe barn
#

write them after every number

weary finch
#

what's a bigger value than uint?

dim halo
#

okay

polar acorn
#

For ints it's not necessary but won't hurt anything

scarlet hull
#

okay

safe barn
rare basin
weary finch
#

it says long, but can I use that in Unity?

rare basin
#

try it

#

and see

thorn holly
#

Is there a way to make certain methods get called before others in a delegate?

polar acorn
thorn holly
#

Or is it all asynchronous

polar acorn
thorn holly
polar acorn
thorn holly
keen dew
#

"My car is broken." "But this is a bicycle?" "Yeah but I haven't touched my car"

weary finch
polar acorn
rare basin
weary finch
#

it says that ulong is an unexpected token in my shader

polar acorn
rare basin
#

why do you need a ulong in a first place?

#

i feel like you dont need it at all lol

#

what shader are you doing

weary finch
#

it's both, it seems to be working on the cpu side, but not in the gpu

weary finch
#

I wanted to save some space by doing some bitoperations on uint and save the last byte, but I was looking for something inbetween uint and ulong

#

but it seems that if the size is not multiple of 4 it cannot be used in shaders, so there's nothing inbetween i guess

orchid trout
#

I am trying to debug some scripts in visual studio but for some reason it cant see or find anything under Packages, only stuff under Assets
How do I fix this and let it debug stuff in packages?

#

when I try to F11 to advance into the script, it brings up a 'cant find this in default path' complaint, with the default path being completely bogus

#

and when I manually go to the file, it lists it as 'external' for some reason

polar acorn
weary finch
#

i will try there then, let's see

rich adder
scarlet hull
queen adder
#

hi everyone... could someone tell me what i could improve about this... game structure... thing... :DDDDD

rapid valve
#

yo can someone help add my idle animation to my character in unity

#

not the x bot the character that I imported

#

bc it seems to not work

#

like I have the animator and the idle animation put into the block put idk why it will not work

polar acorn
queen adder
#

deck.cs holds the card objects and manages them

#

card.cs is a scriptable object thats just there for the card display and everyhting

rich adder
queen adder
#

i mean afaik i could just stuff everything into like three classes and call it a day

#

i just wanna do it the unity way ive read a couple books and it did clear a few things up but i

queen adder
#

i dont know honestly

open sierra
#

Can someone explain to me how the inside of the "if" line of code works? I don't understand why we are using a new Vector3 and not Vector3 by its self? and why did he write transform.position.y and transform.position.z instead of just writting 0, 0

#

reposted since I sent it in the wrong chat

queen adder
#

isnt vector3 a class

rich adder
#

struct

ivory bobcat
queen adder
#

well i was close enough

ivory bobcat
#

The above would be calling the constructor to create a new instance of the type

rich adder
polar acorn
open sierra
#

so you use new Vector3 whenever you have another vector3 in the line?

rich adder
#

no

#

in this case transform.position is a V3 but you cannot modify directly its properties (x,y,z) only read them

#

so you either put another new vector3 that you created earlier or now hence the new()

polar acorn
delicate venture
#

hey guys, quick question, anyone knows how to properly set the cinemachine? The vcam is set to follow the character but clearly thereΒ΄s a delay in that process

open sierra
#

I see

#

tys

rich adder
charred spoke
rich adder
#

^^ you want to remove damping probably

queen adder
#

so you guys are saying as long as the game runs i shouldnt worry about the way i coded it...

rich adder
#

for your own sanity

queen adder
delicate venture
delicate venture
polar acorn
rich adder
#

usually Center mode will throw you off

#

instead use Local/Pivot mode

ivory bobcat
# open sierra so you use new Vector3 whenever you have another vector3 in the line?

The assignment operator (the equal sign) suggests that you're wanting to assign something on the right to the left. Position is a property that is of the type Vector3. Since it's a property, we cannot modify it's members (x, y, z) directly so instead we'll assign it a completely different Vector3 instance. To create a new Vector3, you'd use the new keyword with it's constructor.

queen adder
rich adder
#

langauage is just a tool to achieve a goal

#

you're telling the computer to do X Y Z

#

it doesn't care which language it is

#

its all machine code in the end

ivory bobcat
#

Another common pattern is to copy the Vector 3, modify the particular component and reassign it back to the position propertycs var position = transform.position;//Cache the position position.x = -10;//Modify the x component of the Vector 3 transform.position = position;//overwrite the position property with our updated cacheReminder that properties aren't fields.

queen adder
#

ive used a couple languages before deciding to ultimately switch to c#... and usually you have to come up with your very own creative solutions to problems more often than not... c# on the other hand has everything already covered and its... weird...

ivory bobcat
#

This has the benefit of not creating multiple new vectors which occurs for every call to transform.position

queen adder
#

var feels like cheating tbh

rich adder
queen adder
#

yeah c# right after c++ is definitely a breeze

rich adder
#

I used to think Game Maker Scripting language was hard so I never learned and used all drag n drop componentsπŸ€·β€β™‚οΈ few years later I'm coding in c# strictly πŸ˜†

queen adder
#

are gdscript and gamemaker script even worth learning at this point

#

i mean honestly cant blame you i did the same thing

rich adder
queen adder
#

no point in being a one-trick pony if you can make a game and write a server for the said game in c#

#

definitely

honest haven
#
{
    // Assign your player prefab, camera prefab, and Cinemachine prefab in the Unity Editor
    public GameObject playerPrefab;
    public GameObject CinemachineFreeLook;
    public GameObject GameMananger;

    private void Awake()
    {
        // Check if player, camera, and Cinemachine already exist in the scene
        if (GameObject.FindGameObjectWithTag("Player") == null)
        {
            Instantiate(playerPrefab);
            playerPrefab.GetComponent<Animator>().Rebind();
            Debug.Log("added a rebind");
            DontDestroyOnLoad(playerPrefab);
        }
        
        if (GameObject.FindGameObjectWithTag("FreeLook") == null)
        {
            Instantiate(CinemachineFreeLook);
            DontDestroyOnLoad(CinemachineFreeLook);
        }
        
        if (GameObject.FindGameObjectWithTag("GameManager") == null)
        {
            Instantiate(GameMananger);
            DontDestroyOnLoad(CinemachineFreeLook);
        }
    }
}``` is this the best way to do ddol?
rich adder
#

Oh no..

#

don't name a class "DontDestroyOnLoad"

#

actually its a MB function so it prob doesn't matter...

queen adder
#

definitely weird

honest haven
short hazel
#

And the code won't work

rich adder
short hazel
#

Calling DontDestroyOnLoad on a prefab does nothing at best, throws an exception at worst

short hazel
#

You use the value Instantiate returns and put that in DDOL

rich adder
#

also would just use it in a singleton pattern

honest haven
#

Do you have an example?

#

just so i know the correct direction

rich adder
honest haven
#

So if i went the singleton way. Could i create an essential Loader class. then have all my DDOl on that class

rich adder
#

they can just inherit from that 1 singletonclass and you dont have to do any additonal logic or keep track of anything

honest haven
#

or make the player a singleton

rich adder
#

like per example Foo : Singleton<Foo>

honest haven
#

and add the null check on that

timber tide
# open sierra Can someone explain to me how the inside of the "if" line of code works? I don't...

transform.position is obtained through a property (getter) but there is no setter for independent values of x, y, z; there is only a setter for Vector3 struct as a whole. This means the only way to change the position is to send your own Vector3 struct into transform. Also, since transform.position is a property, the Vector3 information you receive is passed by value because structs are value type, meaning that editing the recieved Vector3 data will not reflect the actual transform.position data unless you send it back.

rich adder
#

you want to avoid writing repetitive code

#

you write DDOL like 3 times in 1 class instead of having class take care of itself by inheritance

honest haven
#

yes i agree thats why i want to get this wight

#

right

rich adder
#

there are many ways to do pretty much everything, ultimetly its up to you. You're the one looking at the code

honest haven
#

ok thanks guys

round moon
#

can some one help me find out where is error from this code ? i learn this course from udemy btwnotlikethis πŸ™

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

short hazel
#

You need to configure VS Code so errors are highlighted in the code directly

radiant glen
short hazel
#

You need an Event System in your scene. It's automatically added when you create a Canvas, so you probably removed it by accident.
Add one, it's what sends events to your UI elements

sullen zealot
#

hi!

mScrollRect.normalizedPosition = Vector2.Lerp(mScrollRect.normalizedPosition, newNormalizedPosition, 10f);

does anyone know why this isnt moving smoothly? it just snaps to the new position

languid spire
#

because that is not how to use Lerp

rich adder
#

learn how lerp values t

onyx tide
#

Is it normal if the moove speed is higher in void FixesUptade than in void Update ?

sullen zealot
#

oh i get it

#

i was using it as a tween function

rich adder
rich adder
round moon
rich adder
#

Visual Studio Code Editor

#

did you read the link at all ?

short hazel
half patrol
#

Hello, beginner here. So I have only small code here and unity executes Debug.Log twice. Why is that?

eternal falconBOT
solemn bobcat
rich adder
#

see where the logs come from

#

nvm

#

thats a constructor

#

kinda invalid for a MB

#

use Awake instead

onyx tide
half patrol
rich adder
#

Monobehavior are slightly different than regular classes, they are instanced by unity

solemn bobcat
onyx tide
half patrol
rich adder
#

should be no errors
you just cannot attach it to a gameobject though.
Show the error maybe ?

scarlet tiger
cosmic dagger
cosmic dagger
half patrol
# cosmic dagger Show us the actual code . . .

... i did.

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

public class Player
{
    int health = 100;

    public Player()
    {
        Debug.Log($"This is health {health}");
    }
}
rich adder
# half patrol

some of those is because the script is still attached to a gameobject

half patrol
#

so it should not be

cosmic dagger
rich adder
#

regular classes can be embedded in MB and then attached to gameobject through that

#

or just instantate it when needed with new()
But they cannot be attached to gameobject directly

cosmic dagger
half patrol
#

i got you guys

#

thank you

solemn bobcat
# onyx tide Ah it works ! thank you so much

Do you mean inputs? I believe inputs by default are configured to match frames. FixedUpdate doesn't align with frames, which might make you lose some inputs. I don't remember if it can be configured differently. I usually separate inputs and movement logic from each other to avoid potential issues.

solemn bobcat
open sierra
#

when should you use "Int" when coding in unity?

half patrol
short hazel
winter prawn
open sierra
solemn bobcat
open sierra
#

gotchu

short hazel
rich adder
winter prawn
sullen zealot
#

hello!
how can i animate a vector2 variable to get another value with leantween?
something like this

var position = new Vector2(0f, 0f);
LeanTween.move(position, new Vector2(100f, 100f), time);

in which the value of position changes as if it was a moving object

amber veldt
#

Hey guys, is there a good tutorial on how to make a bow and arrow 3rd person system?

rich adder
#

probably, search it up

amber veldt
#

Tried, nothing on youtube sadly

#

Well there is... But nothing too convincing

timber tide
#

just do a 3rd person gun tutorial

rich adder
#

what does that even mean

amber veldt
#

And Animation Rigging does not seem to fit, for my case at least

rich adder
#

you're asking about the whole system you aint gonna find much

timber tide
#

gun that shoots arrows

rich adder
#

you have to learn to piece stuff together

#

its all recycled mechanics

sullen zealot
amber veldt
#

Yep, tried but aiming feels clunky, even with today standards

rich adder
#

Leantween was wack for me

#

!code

sullen zealot
#

and how would you do it in dotween?

eternal falconBOT
rich adder
sullen zealot
#

but be able to choose the easing

#

and not have to make a coroutine

keen hill
#

hi im trying to make a thirdperson item pickupscript but im stuck on checking if the item is close to the player(in my example 3f) im trying to do it with the overlapsphere but i dont know how to take exact values out of the array to do stuff with them maybe im trying to do it wrong if you have better ideas let me know
heres the script https://gdl.space/ogijikifox.cs

faint agate
#

Hey guys, I think this can be answered without showing my full script. I have script on a on an object and a reference to my player(rigidbody) on the script, but on start ,it deletes and I get an error " There is no 'Rigidbody' attached to... ". I even have a on start to call the rb

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

am I doing this wrong? Does the object need a rigidbody its self for me to access another(player)

timber tide
# keen hill hi im trying to make a thirdperson item pickupscript but im stuck on checking if...

This where those c# problems come along but iterating through foreach is something you should read into
https://www.w3schools.com/cs/cs_foreach_loop.php

I suggest just go through all the topics on this if you've not. Very basic concepts to go through

modest dust
faint agate
quiet gazelle
#

hello, I get this error:

Unable to find shaders used for the terrain engine. Please include Nature/Terrain/BillboardTree shader in Graphics settings.

What I don't understand is, why do I don't get this error in playmode? Only when I build the game and play via the build. I understand what it wants me to do, but I don't even have that shader it seems, the only shaders I have in Nature/Terrain/ are Diffuse, Specular and Standard.

So what is going on?

Any help is MUCH MUCH appreciated! (PS: I am using Adressables if it makes a difference)

normal smelt
eternal falconBOT
normal smelt
#

oops sorry wait

normal smelt
rich adder