#💻┃code-beginner

1 messages · Page 240 of 1

shell sorrel
#

so yes you want only 1 that never dies that is shared

polar acorn
#

this object should be a singleton

reef totem
#

ok

faint sluice
#

Oh my bad I missed that part

reef totem
#

so ill delete the one in scene 2 is that good

#

will that solve my problem?

polar acorn
reef totem
#

ik

polar acorn
#

you could properly set this as a singleton so you'll be able to add it in every scene and always have one available wherever you start from

reef totem
#

ok

#

let me try

shell sorrel
#

really they should hit the introductory learning content and understand references better

reef totem
#

it sort of works i think

#

let me explain

#

my player is not moving

#

set force is equal to 2000

shell sorrel
#

well double check your player is correctly being referenced by this

#

since am 99% sure it is not

polar acorn
reef totem
polar acorn
# reef totem no

so then why are you expecting it to be using setforce when it's not using setforce

reef totem
mossy bay
#

Just started my first project with Unity and my Object doesn't jump with space bar. Can you guys find out why?
`public class birdscript : MonoBehaviour
{
public Rigidbody2D myRigibody;
public float flapstrength;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) == true)
    {
        myRigibody.velocity = Vector2.up * flapstrength;
    }

}

}
`

reef totem
rocky canyon
#

i think ur trying to ride a horse after you've seen one for the first time in ur life 😄

polar acorn
polar acorn
# reef totem

Okay, so the very first frame that this object exists, you set the current PlayerScript's forward force to whatever setforce currently is

#

Is this object's setforce equal to 2000 on the first frame this object exists

polar acorn
polar acorn
mossy bay
reef totem
#

but i can quickly double check and debug it

#

give me a sec

cinder crag
#

anyone knows how to do this?

polar acorn
rocky canyon
#

since u dont do it in code

reef totem
polar acorn
mossy bay
rocky canyon
#

i just told u

queen adder
rich adder
mossy bay
#

Okay thank you guys

rocky canyon
#

drag the object with the rigidbody into the slot for the rigidbody u created

polar acorn
rocky canyon
#

the one that says None

#

meaning its not assigned

reef totem
#

i mean on the previous scene i set the object already to 2000 so i would expect it to stay like that

polar acorn
#

How are you setting this to 2000 before the first frame this object ever exists

#

Start runs on the first frame this object exists and that is the only time you set the player's force

polar acorn
#

multiple times

reef totem
#

I though u meant it as the first frame this object exists in the second scene

mossy bay
polar acorn
#

I made it very very clear that this runs the first frame the object exists

reef totem
polar acorn
#

it runs the first frame this object exists

#

that's why I am very specifically using those words in that order

rocky canyon
#

ahh digi beat me to it

reef totem
#

oh i think i could get away with that since i was using 2 different objectc for 1 script but now with that ddol it doesnt work like that

#

ok well now that u have helped me with that

#

what do u suggest i do

rocky canyon
#

nope.. thast whats magic about it.. u can have ur gamemanager exist thruout the project

polar acorn
#

and then have your player just use the value from the singleton directly

#

and not have its own copy of the variable

reef totem
#

whats a singleton

rocky canyon
summer stump
#

Look at the singleton page

polar acorn
reef totem
#

ok

rocky canyon
#

its a script that exists (only once) can't have copies.. soo therefor u can make a reference to it. that any script can access at anytime.. anywhere

reef totem
#

but before i read it would u also reccomend i put PlayerScript.fowardForce = setforce; on a void Update

#

like would that also work

rocky canyon
#

why set it more than once?

#

why set it every frame? thats wierd

reef totem
#

yea ig

polar acorn
rocky canyon
#

thats like me asking the time and u start counting non-stop

#

i'd walk away

polar acorn
#

Game Settings are kind of the poster child use case for a singleton

reef totem
polar acorn
#

so read the article I linked and learn

reef totem
#

im just trying to become more familiar

queen adder
rocky canyon
#

well, i'll suggest when u see these new words... like DDOL, additive scene loading, singleton, etc u look them up

#

reading about them yourself is gonna be the best way to become familiar

reef totem
#

ok

queen adder
#

Probably you shoudl learn a little bit more about C#, that would answer many of your question because they dont have anything to do with unity but more like programming

reef totem
#

anyways thanks for the help and i will update u guys soon

rocky canyon
#

good luck 🍀

queen adder
#

forwardForce is a public property that can be assigned to a certain value

reef totem
rocky canyon
#

should be easy to refresh urself then

queen adder
#

well, if you don't know if you can assigne a value of a property it seems that youre knowledge, regardless how many years you did this before, equals to zero 😅

#

so... maybe get a quick code of c# on youtube

reef totem
#

what happens if you put static in front of a variable

#

like what does static do

night mural
#

electrocutes it

#

think of static as meaning that thing is part of the class itself rather than a property on an instance of that class

vocal fable
#

how would you check if there's something between two objects? basically, i want to make an enemy script and if the enemy can clearly see the player the enemy follows the player

summer stump
swift crag
#

or, in this case, consider using Linecast

#

A raycast shoots a ray from a point in a direction

#

A linecast draws a line between two points

#

Both look for colliders that hit the ray or line

#

Ah, there is a difference -- the Raycast page says it ignores colliders that you start inside of, whilst Linecast doesn't say that

#

I wonder if that's actually the case, though...

#

I should definitely be using Linecast more. I have a fair number of places that calculate a ray between two points

timber tide
#

What's the ideal setup for interface component searching in Update()? Layer masking a gameobject with a single component and interface? It shouldn't matter what this script contains beyond the interfaces, right?

#

I was also thinking doing it by unity tags and doing lookups.

shell sorrel
#

got more details

#

like what are you looking up and why

timber tide
#

Overlapsphere bunch of enemies

#

consistently

shell sorrel
#

oh and getting interfaces from that

#

really would just do it the easy way and see if you have any issues

#

like get your stuff and look for the component you need or interface type of what ever

#

if it causes a problem would then implementing some caching

timber tide
#

The script is by far the worst performant one I've got, but this ability system is kind of the main feature so it's expected.

shell sorrel
#

like for rapid fire weapons in the past i would have a dict that maps colliders to components

rich adder
timber tide
#

Like, I have fireball abilities that hit 300+ enemies at once

#

every frame

shell sorrel
#

that way i am not doing constant GetComponents

swift crag
#

So you've got a persistent area of effect that's hitting tons of stuff?

timber tide
shell sorrel
#

also for a persistient area i would use a regular collider

rich adder
#

good ide!

swift crag
#

Consider using trigger enter and exit to keep track of what is and is not being affected

shell sorrel
#

then keep track as things enter and exit

swift crag
#

jinx

shell sorrel
timber tide
#

that does seem smart, but say a fireball that doesn't collide but does constant damage every 0.1 seconds

#

and moves forward

shell sorrel
#

yeah would stil use colldier enter and exit

#

it does damage on its update method

swift crag
#

just make sure the fireball is moving in a way that the physics system can understand!

shell sorrel
#

and adds thigns to a hashset to do damage to

swift crag
#

so, don't set its transform directly

shell sorrel
#

and removes them on exit

timber tide
#

Sound like an idea. I do like queueing my own physics checking methods, but if that's more performant I'll look more into them

vocal fable
#

so i should use linecast?

summer stump
#

Give it a shot

shell sorrel
#

but i think the collider approach is better overall

pallid nymph
#

I tried this mapping thing once, was surprisingly not more performant than GetComponent if I have just 1-2 components... but it was a long time ago and I may have messed it up

timber tide
#

May end up throwing rigidbodies on them anyway just for the interpolation checking

pallid nymph
#

All in all, the profiler is your friend (or the Stopwatch guy)

shell sorrel
blazing estuary
#

yall how to send code

#

!code

eternal falconBOT
blazing estuary
#

oh

#
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;

public class PlayerShip : MonoBehaviour
{
    public float shipSpeed;
    private GameObject enemyShip;
    private float _distance;
    private Rigidbody2D _rb2d;
    
    // Start is called before the first frame update
    void Awake()
    {
        _rb2d = GetComponent<Rigidbody2D>();
        enemyShip = GameObject.FindWithTag("enemy");
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }
    private void Move()
    {
        //transform.LookAt(Vector2.up);
        _distance = Vector2.Distance(transform.position, enemyShip.transform.position);
        Vector2 direction = enemyShip.transform.position - transform.position;
        direction.Normalize();
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90;

        if (_distance > 10)
        {
            _rb2d.AddForce(direction * shipSpeed, ForceMode2D.Force);
            transform.eulerAngles = Vector3.forward * angle;
        }
        else if (_distance <= 10)
        {
            float randomNumberX = UnityEngine.Random.Range(-50, 50);
            float randomNumberY = UnityEngine.Random.Range(-50, 50);
            Vector2 movementsmth = new Vector2(direction.x + randomNumberX, direction.y + randomNumberY);
            float angle2 = Mathf.Atan2(direction.y + randomNumberY, direction.x + randomNumberX) * Mathf.Rad2Deg - 90;
            for (int i = 0; i < 4; i++)
            {
                _rb2d.AddForce(movementsmth, ForceMode2D.Force);
                transform.eulerAngles = Vector3.forward * angle;

            }
        }
    }

}
#

alr so basically

#

is there a way to make it so that the things in the if statement dont happen while the things in the else if statement are happening?

thin hollow
#

why when i instantiate an object, it creates a clone?

vocal fable
blazing estuary
#

even if the if statement is true again

blazing estuary
thin hollow
blazing estuary
shell sorrel
blazing estuary
summer stump
blazing estuary
#

after the for?

shell sorrel
# blazing estuary after the for?

explain what you want better, with a if/if else only 1 or 0 branches of it will run at a time. if you want it to only run a branch only ever once. you set a boolean saying you run it, then check for that in the future

blazing estuary
vocal fable
shell sorrel
#

so in the if else branch set something like hasRun = true

blazing estuary
#

ohh

#

thanks

shell sorrel
#

then in the if add a !hasRun && _distance > 10

blazing estuary
#

you saved prob hours of my life btw

#

thank you

shell sorrel
#

obviously use names that makes more sense for what it means to your game

#

but the idea of it

blazing estuary
#

yes

#

i have a variable called movesmth

#

and well it moves something i guess

shell sorrel
#

it can jsut be a field on your class
private bool _hasRun; or something like that at the top of the class

shell sorrel
#

it will not detect the hit

summer stump
#

As fen said, I believe that both the player and enemy can trigger the linecast

vocal fable
#

i did this

#

the enemy just always follows the player

#

im going mentally insane

wintry quarry
#

so if it was previously able to see the player, and now isn't hitting anything, it will continue to folow

#

there are basically three cases:

  • Your linecast hits NOTHING
  • Your linecast hits something that IS NOT the player
  • Your linecast hits the player
#

you need to handle all three cases, not just two of them

cinder crag
#

i really need help ngl

wintry quarry
#

do you have a separate Capsule Collider from your CC?

cinder crag
#

There's one on the playerobj and one on the emptyobj named "Player"

wintry quarry
#

there should only be the CC, not a separate capsule

cinder crag
#

the playerobj still seems to be in the same place and not come back up with the CC

#

and the radius seem to be skinnier for some reason

#

after crouch i mean

whole idol
#
using System.Collections;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Sprite tile;
    public int worldSize = 100;
    public float noiseFreq = 0.05f;
    public float seed;
    public Texture2D noiseTexture;

    private void Start()
    {
        seed = Random.Range(-10000,10000);
        GenerateNoiseTexture();
        GenerateTerrain();
    }

    public void GenerateTerrain()
    {
        for (int x = 0; x < worldSize; x++)
        {
            for (int y = 0; y < worldSize; y++)
            {   
                if (noiseTexture.GetPixel(x,y).r < 0.5) 
                {
                    GameObject newTile = new GameObject(name = 'tile');
                    newTile.AddComponent<SpriteRenderer>();
                    newTile.GetComponent<SpriteRenderer>().sprite = tile;
                    newTile.transform.position = new Vector2(x,y);
                }
            }
        }
    }

    public void GenerateNoiseTexture()
    {
        noiseTexture = new Texture2D(worldSize,worldSize);
        for (int x = 0; x < noiseTexture.width; x++)
        {
            for (int y = 0; y < noiseTexture.height; y++)
            {
                float v = Mathf.PerlinNoise((x + seed) * noiseFreq, (y+seed) * noiseFreq);
                noiseTexture.SetPixel(x,y, new Color(v,v,v));
            }
        }
    noiseTexture.Apply();
    }
}

shell sorrel
#

"tile" not 'tile'

thin hollow
#

Can someone explain how to get rid of the clone object "DataManager(Clone)" that is coming from this method:

`public class MenuController : MonoBehaviour, IDataPersistence
{
[SerializeField] private List<GameObject> persistentObjectList = new List<GameObject>();
[SerializeField] private List<string> persistentNames = new List<string>();

public static DataPersistenceManager dm;


private void Awake()
{
    if (GameObject.Find("DataManager") == null)
    {
        GameObject newDm = new GameObject();
        
        newDm.name = "DataManager";
        newDm.AddComponent<DataPersistenceManager>();
        newDm.GetComponent<DataPersistenceManager>().GetInstance().SetFileName("game_data.json");
        Instantiate(newDm);
        
    }
    else 
    {
        GameObject temp = GameObject.Find("DataManager");
        dm = temp.GetComponent<DataPersistenceManager>().GetInstance();
    }
    
}`
shell sorrel
#

why Instantiate if you dont want a instance of it then?

short hazel
#

The Instantiate(newDm) is what's doing it

#

Instantiate creates a copy of the object you pass to it

thin hollow
#

basically i want to check the scene is there is a datamanager

#

then if there isnt, create one

polar acorn
short hazel
#

Doing new GameObject() already creates the object in the scene for you

thin hollow
#

ohhhh

#

i didnt know that lol

#

i thought it was just in memory and not in the scene

cinder crag
#

i still need help with this please , i was jsut following this tutorial https://youtu.be/-XNm7dPVVOQ?si=2T1G51VgZE91fn3e

Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!

Join me and learn your way through the Unity Game Engin...

▶ Play video
polar acorn
#

You've cropped those out of your video, what are those set to in the inspector

cinder crag
#

these type of mistakes are the death of me

polar acorn
#

It's also serialized so the value in the code doesn't matter, what is it in the inspector

cinder crag
#

it works nice now so thats good

#

now how do i shrink the player when crouching and then the player grows back up , i already tried these

polar acorn
cinder crag
polar acorn
cinder crag
polar acorn
#

Do you want it to be conditional or not

cinder crag
#

Nope

polar acorn
#

This is not a "good code bad code" thing this is literally "what do you want the code to do"

#

If you don't want to conditionally change the height, then don't change the height conditionally

thorn holly
#

If a kinematic and static body collide, will OnCollisionEnter be called?

thorn holly
#

Thanks!

thorn holly
polar acorn
thorn holly
#

On the static body?

polar acorn
#

The non-kinematic one will need to have a rigidbody on it as well. If you're in 2D I think that rigidbody specifically needs to be "dynamic" but in 3D a "static body" is just a collider with no rigidbody

thorn holly
polar acorn
thorn holly
#

That would work. So if I have a wall and a ball that would bounce off it, but neither do physics simulation, I make the wall a dynamic rigidbody, freeze position contraints, then make the ball a kinematic body?

polar acorn
#

Possible. tryitandsee

thorn holly
#

Will do, thanks

pallid nymph
#

how would the ball bounce?

#

if it's not doing physics sim

polar acorn
minor patio
#

so I'm trying my hand at a character creator app for a table-top rpg and I'm trying to deal with abilities ("Competencies & Specialisations") - I've got an issue where my list of Competencies is being called multiple times (the list is initialised in an Awake method) & I can't think of how to debug it. I've got another issue where the competency variable is supposed to be 'got' from the list index, but my debugs are generating Null Reference Exceptions on the variable and I again can't figure out how to check for the variable having an assigned value. Not posting code until I'm asked for it thinksmart Any insight welcome

polar acorn
#

Show code

#

And show the specific error

cinder crag
polar acorn
cinder crag
polar acorn
#

If that's what you want to change the scale of yes

cinder crag
#

Alrighty then

minor patio
#

oops
sorry

polar acorn
#

!code

eternal falconBOT
polar acorn
#

Show Competencies.cs

minor patio
#

define "Large Code Blocks" XD
this is all from Competencies.cs

polar acorn
#

Just send the full class on a bin site

minor patio
#

sorry

summer wasp
#

how can i make arrow point towards the velocity direction? considering its face is not the arrow tip

polar acorn
polar acorn
polar acorn
summer wasp
polar acorn
summer wasp
#

i didnt get it

#

sorry about my grammar

polar acorn
#

Which direction of the arrow do you want to point in the direction of velocity

minor patio
summer wasp
#

i dont know exactly how to explain

polar acorn
summer wasp
#

up

polar acorn
#

Then set transform.up to velocity

polar acorn
summer wasp
polar acorn
summer wasp
#

ooh thanks

minor patio
#

"Try logging the index and competency as you get it in the loop"
There's a loop?!? A sound suggestion, tho

polar acorn
#

Although looping over it and printing them all would be a good debugging step

thin hollow
#

int he editor for sprite renderer, is "Order in layer" the same as <SpriteRenderer>().sortingOrder

minor patio
polar acorn
#

In Awake, add this:

foreach(Competency c in competencies){
  Debug.Log(c);
}
#

See if anything's in it before you add all the other stuff in awake

minor patio
polar acorn
#

look for other scripts that reference the competencies list

#

Wait, hang on a tick:

#

Why is your competency object a child object of your Competencies list

#

Competencies is a Monobehaviour, you can't create instances of it with new

#

You should have been getting a ton of warnings about that

minor patio
polar acorn
minor patio
polar acorn
#

Hm, there should definitely be warnings about creating a MonoBehaviour with new. Still, there's zero reason for your Competency objects to extend Competencies. You can't create them with new, so you're going to get null out of it

minor patio
minor patio
polar acorn
minor patio
minor patio
#

the list is now a list of Competencies - there's no child class of Competency anymore

#

not that that's helping me...

shell sorrel
#

that is confusing naming

teal viper
#

You'd think it's plural of the same object

shell sorrel
#

generaly if giving something a plural name, it will be for a collection

#

or a object that contains many of something

polar acorn
#

Why does this object contain a list of itself

#

How are you adding itself to the list since you can't create itself with new

minor patio
polar acorn
minor patio
#

I would like the list to be a list of skills that a character can acquire
I want this list to contain functional code XD

polar acorn
#

Okay, so what is a skill that a character can aquire

#

what represents that concept in your code

shell sorrel
#

so want each one to be able to define some functions?

minor patio
polar acorn
#

Is it a GameObject, a ScriptableObject, a string, a POCO, an enum

#

it can be a lot of things

shell sorrel
#

also how much stuff is the same between skills

minor patio
shell sorrel
#

just a regular C# object

polar acorn
shell sorrel
#

not a monobehaviour

polar acorn
#

As in not inheriting from anything, just a class with data and maybe some functions

shell sorrel
#

how much do skills have in common vs not in common

minor patio
shell sorrel
#

so make a base class that repersents the most generic version of a skill

#

then have other classes extend from it, for the more concreat versions of the skills

#

that can override methods

minor patio
minor patio
#

I need a break - thanks for your input, @shell sorrel , @polar acorn

#

"You've given me a lot to think about" XD

shell sorrel
#

its always good to take breaks, gives you time to think about stuff in the back of the mind

minor patio
#

😉

#

later

thin hollow
#

how to I reference this aka add a new item to this in event trigger via script

meager raptor
#

purpose: when unit health reaches 0, it should get destroyed

error: as soon as i start the game, literally all the units get destroyed aka the game objects get deleted. does anyone know why this is happening?

timber tide
#

debug.log everywhere you set health

meager raptor
#

^ as soon as i start the game

#

its happening to both player n enemy units

#

idk where the problem is

timber tide
#

if you want to post the script on a pastebin site, go for it because there's nothing here that shows you setting the health

meager raptor
#

wait i kinda found the error still need help tho

#

problem is, base health has values but when game starts the current health is still 0, it should be equal to base health

#

what's the solution for this?

timber tide
#

time to debug baseStats.health then

#

it's less likely an editor error and more that you're setting it incorrectly in your code

meager raptor
#

not sure if this part of the code is the problem but i'll just put it here anyway

timber tide
#

so your baseStats is a scriptable object, where are you referencing it and how are you using it

meager raptor
timber tide
#

right, but you aren't setting baseStats.health at all right? You're just serializing it to the script and using that exact instance?

meager raptor
#

yeah i set it in the unity program

#

like this

timber tide
#

I don't see where you're creating an instance of base though

#

oh, that could be a problem

#

just to test something, remove everything from Base and put it directly into UnitStatTypes

#

otherwise, create an instance of Base inside of UnitStatTypes

#

and serialize that

warped vale
#

help please

timber tide
#
public class UnitStatTypes : Scriptableobject
{
    [field: SerializeField] public Base BaseData { get; private set; }

    [Serializable]
    public class Base
    {
      [field: SerializeField] public float health { get; private set; }
    }
}```
warped vale
#

what do i do with that

rocky canyon
#

whats this doing there?

warped vale
#

its a multiplayer package

summer stump
#

Beat me to it. Remove that

rocky canyon
#

thats wrong.. the syntax is wrong

warped vale
rocky canyon
#

doesnt matter... its written wrong..

summer stump
summer stump
timber tide
summer stump
#

But that is not how you use it

teal viper
rocky canyon
#
namespace Photon.VR
{
  [CustomEditor...
#

there shouldnt be random text between two opening brackets like that

warped vale
summer stump
rocky canyon
#

now ur brackets missing..

summer stump
#

Just the word photon needed to be removed

#

You should... probably learn c# before attempting multiplayer

meager raptor
teal viper
# warped vale like this?

I super highly strongly recommend to stop right there and do some C# basics learning before even thinking about multiplayer.

warped vale
#

alr

teal viper
#

If you keep doing what you do with your current level, not only you're gonna fail, but people would refuse to help you too.

rocky canyon
#
using UnityEditor;
using UnityEngine;

namespace Photon.VR
{
    [CustomEditor(typeof(PhotonVRManager))]
    class PhotonVRManagerGUI : Editor
    {
        private Texture2D logo;
    }
}```
#

make sense??

timber tide
rocky canyon
warped vale
#

now this showed up

teal viper
#

I guess you didn't listen to what I said...

warped vale
rocky canyon
#

it can't find Pun in the namespace ur using..

#

why? idk

timber tide
# meager raptor

Wherever you're setting the SO can you write this:

public UnitStatTypes statTypes;

public void Start()
{
  Debug.Log("Health is: " + statTypes.BaseData.health);
}```
meager raptor
#

yeah 1 sec i have to amend the code

timber tide
#

there's a reason I've got private setters there

meager raptor
#

yeah but then i get these small errors x5

summer stump
#

I saw baseData in mao's code

timber tide
#

you're missing an accessor

#

my code creates/requires one more dot operator

meager raptor
timber tide
#

Dont return by UnitStatTypes, just send the full reference

#

oh ok you're writing to the SO it seems?

meager raptor
#

yeah

#

appreciate the help btw

timber tide
#

im guessing you were just writing to a single instance of an SO and reusing that single instance everywhere

meager raptor
#

👍

timber tide
#

so why exactly are you setting the stats in the inspector, but then set them to another value in code?

meager raptor
#

wait no im not tryna do that im just setting em in the inspector and then making another variable and setting the current health as the base health when booting the game

#
currentHealth = baseStats.health; ```
just like this
#

that's the aim anyway but it doesnt seem to be working

timber tide
#

Set the return type to just UnitStatTypes for GetUnitStats

meager raptor
#

okay, still with the code u provided above?

timber tide
#

yeah

#

then change your PlayerUnit to have a field of UnitStatTypes

#

instead of Base

#

so this way they get the instance of the SO instead of just the nested class

meager raptor
#

gotcha, what am I replacing in the red swiggles

timber tide
#

basically, serialization issues with the nested class and you're trying to access it directly instead of using the actual instance of the SO (or rather you're creating independent instances of the inner class? idk but you shouldn't need to reference by these inner classes)

#

so if unit has Base instance it needs a UnitStatTypes instance

meager raptor
#

ah okay

cosmic dagger
#

does it need to be a nested class of an SO?

meager raptor
#

its 2am rn gotta wake up at 8 so ima go now but i appreciate the help and ill let u know once i solve so u wont be left hanging @timber tide thanks for the help

timber tide
thin hollow
#

how do I make 2 seperate events, right now im getting the hover and down function when i mouse hover



public void AddEventData(GameObject newObj)
{
    List<EventTrigger.Entry> events = new List<EventTrigger.Entry>();
    newObj.AddComponent<EventTrigger>();
    EventTrigger trigger = newObj.GetComponent<EventTrigger>();
    EventTrigger.Entry entry1 = new EventTrigger.Entry();
    EventTrigger.Entry entry2 = new EventTrigger.Entry();
    events.Add(entry1);
    events.Add(entry2);

    entry1.eventID = EventTriggerType.PointerEnter;
    entry2.eventID = EventTriggerType.PointerDown;

    entry1.callback.AddListener((data) => { OnPointerEnterDelegate((PointerEventData)data); });
    entry1.callback.AddListener((data) => { OnPointerDownDelegate((PointerEventData)data); });

    
    foreach (EventTrigger.Entry e in events) 
    {
        trigger.triggers.Add(e);
    }
    
}

public void OnPointerEnterDelegate(PointerEventData data)
{
    Debug.Log("OnPointerDownDelegate called.");

    selectorController.Hover();
}

public void OnPointerDownDelegate(PointerEventData data)
{
    Debug.Log("OnPointerSelectDelegate called.");

    selectorController.Select();
}
ivory bobcat
thin hollow
#

im not sure how it works

ivory bobcat
#

Right now you're adding them both to entry1

thin hollow
#

ohhh

#

ok

nimble apex
#
      if (result == 1 && bacResult.banker == 6 && history.bac_type == int.Parse(BacOption.nonCommision))
      {
        Text text = gameObject.GetComponentInChildren<Text>();

        gameObject.GetComponent<Image>().sprite = BW6Hframe;

        text.text = LanguageDataScript.Instance.AssignJsonKeyToContent("BANKER_WIN_6_HALF");

        if (LanguageDataScript.Instance.LanguageCode == LanguageDataScript.LanguageCodeRes.ENG)
        {
          text.fontSize = 42;
        }
        else
        {
          text.fontSize = 36;
        }
      }```

this code has a "invalid AABB in AABB" error
#

and that error wont even tell me why and whats wrong

nimble apex
#

this is the error, very special, no stacktrace at all

#

thats all of it

#

and because of that, the function has broken

#

i know where it is just because it happened after i made the code above

timber tide
#

time to use the debugger

#

and break point it

teal viper
nimble apex
#

and all related base class and subclasses dont even involved in doing scroll rects

teal viper
#

Do you have a UI that does have it?

nimble apex
#

btw, restart wont fix that

twilit pilot
nimble apex
#

can you ignore or suppress this warning?

timber tide
#

I usually see it when my elements invert into themselves

#

or become 0

nimble apex
#

and that boolean is checking a server data (integer) , and comparing it with an enum

twilit pilot
#

the times I've had it, it's been some scroll rect/UI element set to a width of -0.0008 or something silly

nimble apex
#

before i added that boolean, everything works fine

#

yo WTF

#

git sourcetree has new commit

teal viper
#

Finding the scroll rect that causes the error would be the first step to fixing it.

nimble apex
#

aight

#

ok sry guys

#

maybe its the commit?

teal viper
#

Maybe.🤷‍♂️

nimble apex
#

the commit has a change in one of the main UI

#

nope

#

that commit doesnt even do anything

#

i reverted or pulled the changes , both not working

#

i gonna delete the boolean, to see if a checking of an integer really screw this up

#

ok

#

cant

teal viper
#

You don't just check bool/int though, you set sprite, text and font size. All of these could be related.

nimble apex
#

because the UI it changes are the parent of this one

#

and that change commited 10 min ago

teal viper
#

Well, ui elements can affect each other depending on the setup.

#

So, even small changes like adding text, could be affecting elements on the other side of the canvas.

potent nymph
#

I'm in a situation where I have to use NuGet to install a package for a Unity project. I've never used the package manager before, and I'm confused as to what checkbox I need to tick to install the package

#

If I don't have anything checked, it won't let me install it. Do I have to check everything (Project)?

uncut shard
#

My capsule flickers and shakes when it goes on the side

indigo python
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ColliderTrigger : MonoBehaviour
{

public LogicScript logic;


void Start()
{
    logic = GameObject.FindGameObjectsWithTag("Logic").GetComponent<LogicScript>();
}

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

private void OnTriggerEnter2D(Collider2D collision)
{
    logic.addScore();
}

}

This code tells me :
Error CS1061 'GameObject[]' does not contain a definition for 'GetComponent' and no accessible extension method 'GetComponent' accepting a first argument of type 'GameObject[]' could be found (are you missing a using directive or an assembly reference?)

Not sure what this is telling me. I've used GetComponent often and never ran into an error like this.

wintry quarry
#

You're trying to call GetComponent on an array

#

Which naturally doesn't make much sense

indigo python
#

I'm following a tutorial and this is the exact code he wrote and worked though. Hmm

wintry quarry
#

It's not

#

You wrote it wrong

#

You used the plural version of FindGameObjectsWithTag

nimble apex
#

god dammit , found it

#

pretty horrifying

cosmic dagger
foggy lion
#

I'm using coroutines to time movement between transform.Translate, but when I stop it upon colliding with ground, it moves once more before stopping, code below.

using System.Collections.Generic;
using UnityEngine;

public class FallingBlocksScript : MonoBehaviour
{
    public bool DoneMoving;
    public bool CanMove = true;
    public float BlockFallDelay = 2.0f;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(FallDelay(0.0f));
        CanMove = true;
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            CanMove = false;
            Debug.Log("BlockTouchingGround");
            StopCoroutine(FallDelay(0.0f));
        }
    }

    IEnumerator FallDelay(float v)
    {   
        if (CanMove == true)
        {
            yield return new WaitForSeconds(BlockFallDelay);
            transform.Translate(0, -0.5f, 0, Space.World);
            StartCoroutine(FallDelay(0.1f));
        }
    }
}```
#

I can provide a video if needed

rich adder
cosmic dagger
rich adder
#

You should store it in a variable of type Coroutine if you want to stop coroutine

foggy lion
#

Alright

nimble apex
#

the width and the posx of the UI depend on this variable

indigo python
nimble apex
foggy lion
rich adder
teal viper
nimble apex
#

m_columnNum is 0 , because bool failed

teal viper
nimble apex
#
    {
      m_columnNum = m_betDetails.GetComponent<BacBetDetails>().m_columnNum;
    }
    else
    {
      Debug.LogError("m_columnNum error! value cannot be 0");
    }
``` i gonna pop an error instead
#

so i know whats wrong

#

ok ty

foggy lion
# rich adder https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

Am I doing it right?

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

public class FallingBlocksScript : MonoBehaviour
{
    public bool DoneMoving;
    public bool CanMove = true;
    public float BlockFallDelay = 2.0f;

    private IEnumerator crouton;

    // Start is called before the first frame update
    void Start()
    {
        CanMove = true;
        crouton = FallDelay(BlockFallDelay);
        StartCoroutine(crouton);
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            CanMove = false;
            Debug.Log("BlockTouchingGround");
            StopCoroutine(crouton);
        }
    }

    IEnumerator FallDelay(float v)
    {   
        if (CanMove == true)
        {
            yield return new WaitForSeconds(BlockFallDelay);
            transform.Translate(0, -0.5f, 0, Space.World);
            StartCoroutine(crouton);
        }
    }
}```
foggy lion
#

Damn

#

Man, this is confusing...

#

or maybe I'm just dumb

rich adder
#

its in the docs how you do it..

#

did you even read what I sent?

foggy lion
#

Yes

#

And I thought I followed it correctly

rich adder
#

wait nvm u did it in start

nimble apex
#

normally i wont cache it into a variable, i will just call it like a function with startcoroutine ,

nimble apex
#

do it directly like this

rich adder
#

how do you stop it then

#

doesn't have to be endless, you can stop if something is taking 7 seconds but you want to interrupt in 3

#

oh nvm your msg disappeared lol now minelooks out of context

nimble apex
#

dw im here , thats enough lol forget about the disappeared text

cosmic dagger
rich adder
#

you forgot to assign it again to StartCoroutine(crouton); in FallDelay

foggy lion
#
using UnityEngine;

public class FallingBlocksScript : MonoBehaviour
{
    public bool CanMove = true;
    public float BlockFallDelay = 2.0f;
    public float BlockFallDistance = 0.5f; 

    private Coroutine fallingCoroutine;

    // Start is called before the first frame update
    void Start()
    {
        fallingCoroutine = StartCoroutine(FallRoutine());
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            CanMove = false;
            Debug.Log("BlockTouchingGround");
            StopCoroutine(fallingCoroutine);
        }
    }

    IEnumerator FallRoutine()
    {
        while (CanMove)
        {
            yield return new WaitForSeconds(BlockFallDelay);
            transform.Translate(0, -BlockFallDistance, 0, Space.World);
        }
    }

    private void Awake() 
    {
        CanMove = true;
    }
}```
rich adder
#

also instead of == tag use .CompareTag()

foggy lion
foggy lion
rich adder
#

much

foggy lion
#

Alright, I'll do that at least lol

#

Thanks for the help

summer stump
vale karma
#

https://paste.ofcode.org/U5aPjSGbmNLeVQ2BwWqy6J
Hello again, im getting this error from Unity. I followed an inventory system tutorial that was really well documented. I checked line for line for anything different, and he also had serialization and save issues, but at the end he solved his issues, but I got this issue he didnt have.

thin hollow
#

anyone help me with Lerp within coroutine, i dont get why its not working:

{
    Debug.Log("Lerp");
    startPos = obj.transform.position;
    Vector3 target = new Vector3(4f, 8f, -1f);
    float timeElapsed = 0;
    float totalLerpTime = 5;

   
    
   
    while (timeElapsed < totalLerpTime)
    {
        obj.transform.position = Vector3.Lerp(startPos, target, (elapsedTime/ speed));
        timeElapsed += Time.deltaTime;

        yield return new WaitForEndOfFrame();
    }

    Debug.Log(obj.transform.position);
}

vale karma
cosmic dagger
#

to get a percentage, you divide the current value by the total value . . .

thin hollow
#

ah

#

i missed that

#

thank you!

cosmic dagger
#

speed — in this context — does not appear to be the total value. we don't even know what it is set to . . .

thin hollow
#

but even changing that to totalLerpTIme it still doesnt work

cosmic dagger
#

also, set the position to target after the while loop to ensure it's at the final position, because when timeElapsed is not less than totalLerpTime, it will not run the code to set it to target . . .

#

do you need to WaitForEndOfFrame? using null will wait until the next frame . . .

thin hollow
#

i dont think it matters

cosmic dagger
#

do both of the logs appear?

thin hollow
#

yes

cosmic dagger
#

within the while loop, log the elapsedTime or the position to see if the values update . . .

thin hollow
#

elapsed timeis working

#

but it isnt changing position

cosmic dagger
#

then you need to check startPos and target . . .

#

or make sure you're updating the correct GameObject . . .

thin hollow
#

i mean it looks all good

#

so is the second parameter in Vector3.Lerp the final position you want to get to?

#

ah fuck

#

i think i used the wrong variable

cosmic dagger
#

yes . . .

thin hollow
#

i got it

#

ty for the help!!

cosmic dagger
#

it doesn't matter if it looks good. it needs to be correct and work properly. always check every variable used. the program will do exactly what you tell it you. never guess, always confirm . . .

robust prism
#

Hi there, I am currently making a tile based game where the player's movement is discrete, which means that the player will move from (0,0) to (0,1) instantly, without going through any decimal points and stuff. Since this is the case, collision detection must be done manually whenever the user gives an input for the player to move in game, and I have a question regarding this:

Question
What is the best way to implement this kind of tile based system where data and information about the block can be accessed easily without too much spaghetti?

My Current Approach
I created a new monobehavior class called "Tile" that stores data about the tiles (like isMovable, isInteractable,tileType etc..), and stuck that on my different tile gameobjects, and in a manager, there would be a long if else just to identify the object (which, of course, is definitely not the best method, and the brains in my braincells really hate it), then, I would create a large 100x100 Tile 2d array to store all the tiles (this was created based on the assumption that my game level will not exceed the 100x100 range).

My small idea
Use inheritance child classes to store the different required data on the tiles, and retrieving them would be quite nice. However, the problem is that, since my array is an array of tiles, so I can only get the tile class, cant really get the child classes and their properties

Any help about this matter is really really appreciated! (I have been losing my mind concerning this problem for the past 4 days and I haven't found a solution myself by experimenting, or searching through the internet). Thanks!

teal viper
#

But if you really want to, you can cast the base type to the desired type and if it's not null, you would be able to access the child class properties

potent nymph
#

this is a Unity port of a package that I need for my project, but I'm unsure how to download it to include in my project. Usually I'm used putting the git url in the package manager or downloading a unitypackage file, but this repository doesn't have any of those https://github.com/WulfMarius/NAudio-Unity.git

GitHub

Port of NAudio to the Mono subset used by Unity3D. Contribute to WulfMarius/NAudio-Unity development by creating an account on GitHub.

#

I tried downloading the zip and putting the files into my assets folder, but that resulted in namespace errors everywhere

robust prism
tough lagoon
#

Looks like its for modding unity games, not unity game development

potent nymph
#

I see, that's a shame

#

I used the main NAudio package, which worked in editor but webgl builds don't support dlls

hot wave
#

how to make box collider be the same shape as mesh?

queen adder
#

use mesh collider

faint sluice
faint sluice
#

For most use cases using simple colliders is preferable

queen adder
#

what they want, what you give, it's not that bad anyways

hot wave
#

thank you yappy, sexy UnityChanOkay I was using a low poly for mesh

teal viper
robust prism
#

ahh, I'm currently outside now, maybe I'll ping you when I get back home, is that alright? Thanks for your help!

teal viper
robust prism
#

ok!

vale karma
#

is there correlation between the animation/animator and a Movement State machine? I want to start implementing some animations, but im worried how ill implement it into my state machine

noble forum
#

hi, anyone knows why OnMouseDown() doesnt work for me? it does nothing when i click on object with box collider (3d unity)

vale karma
#

whats the code look like for that method?

noble forum
#

public class Card : MonoBehaviour
{
    private CardGameManager gm;
    public int handIndex;
    public bool HasBeenChecked = false;
    public GameObject PlayButton;
    public GameObject BackButton;
    private Vector3 originalPosition;
    private Vector3 enlargedScale;

    private void Start()
    {
        gm = FindObjectOfType<CardGameManager>();
        originalPosition = transform.position;
        enlargedScale = transform.localScale * 3; // 300% enlargement
    }

    private void OnMouseDown()
    {
        Debug.Log("Card clicked!");
        if (!HasBeenChecked)
        {
            transform.position += Vector3.up * 5;
            HasBeenChecked = true;
            gm.availableCardSlots[handIndex] = true;
        }
        else
        {
            PlayButton.SetActive(true);
            BackButton.SetActive(true);
            transform.position = Vector3.zero; // Move to position 0,0,0
            transform.localScale = enlargedScale; // Enlarge by 300%
        }
    }

    public void BackOnHand()
    {
        transform.position = originalPosition; // Move to the original position
        transform.localScale /= 3; // Decrease size by 300%
        PlayButton.SetActive(false);
        BackButton.SetActive(false);
    }

    public void PlayCard()
    {
        // Different outcome for every card


        Invoke("MoveToDiscard", 2f);
    }

    public void MoveToDiscard()
    {
        gm.discardPile.Add(this);
        gameObject.SetActive(false);
    }
}``` not finished one, but this function should work
stuck jay
#

Does Debug.Log("Card clicked!" work?

noble forum
#

no

stuck jay
#

PlayButton and BackButton weren't set

#

Look at the script on the object

noble forum
#

i know

#

it doesnt matter

stuck jay
#

Actually yeah, that's weird

noble forum
#

im not finished with the script yet, but it has no effect on clicking

stuck jay
#

OnMouseDown is called when the user has pressed the mouse button while over the Collider.

noble forum
#

i know

languid spire
#

Not 100% sure but you may need to add a Physics Raycaster to your camera

noble forum
#

i can click on buttons

languid spire
#

but buttons are UI objects, your Card is not

noble forum
languid spire
#

Is the event system recognising your card?

hot wave
#

can I use hit.transform instead of hit.collider?

#

or different uses

#

confused because different tutorials uses different things, but I want to fuse the functions

north scroll
#

hey im trying to create a character controller, currently the player moves up and down as well even though there are no key binds for it. I want to limit the movement to only move left and right, and i tried accessing the x value of the readvalue but doesnt work

teal viper
languid spire
north scroll
#

wouldnt that affect the jump of im continiously setting Y to 0 and I add a jump button / function ?

languid spire
#

yes, of course, so you would need to do that conditionally

north scroll
#

so like if jump button not pressed, y = 0 ?

#

!OnJump() think

#

im using new input system btw

languid spire
#

Not really. it will depend how you code your jump logic, will Input[move] play a role in that?

north scroll
#

i dont think so. I plan on using addforce, I think thats the most straightforward way

#

and limiting it to one jump so its not spammable and add too much force

noble forum
languid spire
#

then always setting move y to zero will have no effect on your jump as it is merely zeroing out the input from the Move action

north scroll
#

would it be better if I use AddForce instead for everything and just set a cap of how high the addforce can go ?

#

that way if I continiously hold the analog stick it doesnt endlessly get faster

languid spire
languid spire
north scroll
#

:(

noble forum
#

Ill answer when i will start unity on school PC lol

faint sluice
#

Is there a way to detect when user has clicked mouse, without using update?
(Click doesn't have to be necessarily on the gameObject with script attached)

faint sluice
languid spire
#

tbh I've not used this for a while, I seem to remember that if you attach the script to the EventSystem then it will pick up everything

north scroll
#

my jump method makes my character jump immediately, I tried Forcemode2D.Impulse, but that doesnt apply any up force to the character.

icy junco
#

what would be best networking for an fps multiplayer?

teal viper
icy junco
#

what do you mean?

teal viper
#

Exactly what is sounds like.

icy junco
#

so a server that you setup yourself?

teal viper
#

Server, or peer to peer setup. Depends on what you need.

icy junco
#

allright so better setup a server then just using fishnet or photon

teal viper
#

If you can do it and the time and effort is worth it, sure.

icy junco
#

so when setting up a server do you need like a regular old computer to make it ?

teal viper
#

No... It depends a lot on how you're connected to the internet(provider), the project requirements, desired scale and 100500 other factors.

#

Networking is an advanced topic and even major developer studios don't get it right.

#

My point is: if you're a beginner, don't even think about networking. Do the learning, develop a single player title. Once you're at least intermediate+ overall, you can maybe start a networking project.

icy junco
#

allright thanks a lot

languid spire
#

Networking is the ultimate Catch-22 situation, you can only do it well if you already know how to do it well

warm flame
#

is there anyone that could help me with my problem when i press E or mouse0 on the weapon i want to pick up it just goes invisble when its picked up and it still shoots and stuff

teal viper
#

A video of the issue might be helpful as well.

pliant marsh
#

is there any way to change the tag of clones of an object. This script is for spawning circles in random coordinates to the right of the screen so that the main player(the square) has to dodge them. The scripts creates clones of the circle just fine but for some reason the clones dont keep the istrigger is true from the original circle. The clones also dont keep the tag of the original circle either. I was able to fix the is trigger part by just always setting it to true but I'm not sure how to fix the tag problem. I tried just typing Gameobject.tag = Rock(the tag i want it to have) right after line 25 but it came up with an error.

#

this is the error that occured

teal viper
#

Why would you delete the part that you're asking about..?

languid spire
pliant marsh
pliant marsh
#

i put it back in the script

pliant marsh
languid spire
#

does that look like a.tag ?

pliant marsh
#

i created a tag called Rock

#

but only the original circle has it

#

the clones dont

languid spire
#

GameObject is the class, not the instance of the class you are trying to change

pliant marsh
#

oh

gaunt ice
#

!ide

eternal falconBOT
pliant marsh
languid spire
#

I have told you already, twice

pliant marsh
#

okie

pliant marsh
#

thank you

north scroll
#

so my debug.log of the move goes to -1 the first time I move left, but when I turn right, it stays at positive 1 even if I have the left analog stick going left. Im trying to add a dash function and thought it'd be easier if I just add a force in the direction of the analog stick, but not sure how id be able to get it to dash left if the move.x never goes negative aside from the first time

drowsy plinth
#

Hello guys, i follow the Little Adventurer: Learn to make a 3D action game with Unity tutorial of Single-Minded Ryan in udemy, to make a 3d action game and i have an issue about raycast hit for damage system.
I added a box collider to another object on child of my character and set the box collider, i just wanna create raycasthit but raycast hit is stuck some point and doesn’t work like i wanted.
It doesn’t go through z-axis of box collider, why it happened? Here’s my gizmos method:
private void OnDrawGizmos()
{
damageCasterCollider = GetComponent<Collider>();
if(damageCasterCollider == null)
{
Debug.Log("a");

}
RaycastHit hit;

Vector3 originalPos = transform.position + (-damageCasterCollider.bounds.extents.z) * transform.forward;

//Debug.Log("Transform Position: " + transform.position);
//Debug.Log("I dont know wtf is it: " + (-damageCasterCollider.bounds.extents.z));
//Debug.Log("Standart transform forward value: " + transform.forward);
//Debug.Log("Original position: " + originalPos);

//Debug.Log("I dont know wtf is it: " + (damageCasterCollider.bounds.extents));
bool isHit = Physics.BoxCast(originalPos, damageCasterCollider.bounds.extents / 2, transform.forward , out hit, transform.rotation, damageCasterCollider.bounds.extents.z, 6);;
Debug.DrawLine(originalPos, hit.point);
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(hit.point, 0.3f);

if (isHit)
{
    
    Gizmos.color = Color.yellow;
    Gizmos.DrawSphere(hit.point, 0.3f);
}

}

icy sluice
#

does anyone know an asset for sound occlusion?

slender cargo
#

Right so I have a array for some cards, I would like 5 cards to display on the screen at a time. Currently the player can scroll through the displayed cards. But I want it so when it gets to the end of the displayed cards, It removes the first displayed card and then adds a new displayed card from the array.... But I'm not sure how I'd code that?

#

so lets say I have 15 cards, I only want 5 to display at a time. Just need to be able to cycle through the array

#

and when I get to the end of the array, It starts from the beginning again

#

I can do it with 1 card easily

#

but not sure how to do it with 5 cards and then adding cards which are not currently in the scene

gaunt ice
#

you need a sliding window
btw you will never show (magnify) the last card

slender cargo
#

For example 1,2,3 is displayed

slender cargo
gaunt ice
#

or cicular buffer (queue)
you cant use c# built-in one since its doesnt support random access
eg if you have an array and you want to show 4 cards at once
1 2 3 4 5 6 7 8
h t
then you show the card from h to t, each time to you turn left: h-- and t--, turn right: h++ and t++ and mod the queue capacity

slender cargo
#

I could add the cards onto the Scroll view UI element and scroll to only show the cards in which I want displayed?

gaunt ice
slender cargo
buoyant rune
#

how do u change that camera size to a different resolution size

queen adder
#

All right guys I have big issue in my mind. So let's imagine it, I have created two scripts; first one calls "Gun" and other one is "GunController". And I didn't write anything into "Gun" script. As you can see I writed these codes that i sended in picture. But I have question in my mind. As you can see there is parameter calls "startingGun", also I have prefab weapon. I didn't understand how can I assign this weapon prefab as "Gun" type parameter. prefab is gameobject but "Gun" is just script.

low path
#

Are you saying that you dragged your prefab object to the StartingGun in the inspector and are confused how you can assign a prefab to a variable that isn’t “gameObject” type?

low path
#

If so, the answer is just that Unity is smart enough to find the correct component on the prefab you drag in in the inspector.

#

If your prefab has a component of the variable type you are assigning, Unity will just assign your prefab’s component to that variable.

queen adder
#

I didn't put anything on this prefab. Literally nothing

low path
#

Do you have a gun script on the prefab at all?

queen adder
#

and I'm suprised that i didn't get any error. Also as you can see, when I created the new gun i signed as Gun

low path
#

Even an empty one?

queen adder
#

Literally nothing

#

none

low path
#

Can you show the inspector for your gun prefab?

queen adder
#

I'm not able to reach the inspector bcs im on another pc

#

so basically "Gun" script type can store prefabs?

keen dew
#

Come back when you have the project open and you can check what you actually have

quaint thicket
#

I can't get my keyboard WSAD movement to work. It doesn't detect when the buttons are pressed. Any ideas?

using UnityEngine;
using UnityEngine.InputSystem;

public class WSAD : MonoBehaviour
{
    public GameObject GO;
    public CharacterController characterController;
    private InputAction movementInput;
    private Vector2 movementDirection;

    [SerializeField] private float movementSpeed = 5f;

    private void OnEnable()
    {
        movementInput.Enable();
    }

    private void OnDisable()
    {
        movementInput.Disable();
    }

    private void Awake()
    {
        GO = GameObject.Find("Model");
        characterController = GO.GetComponent<CharacterController>();

        // Initialize the movement input action
        movementInput = new InputAction("Movement", InputActionType.Value, "<Keyboard>/wsad");
        movementInput.Enable();

        // Register the movement callback
        movementInput.performed += ctx => movementDirection = ctx.ReadValue<Vector2>();
        movementInput.canceled += ctx => movementDirection = Vector2.zero;
    }

    private void Update()
    {
        // Move the player based on input
        Vector3 movement = new Vector3(movementDirection.x, 0f, movementDirection.y) * movementSpeed * Time.deltaTime;
        characterController.Move(movement);
        Debug.Log("Update - movement: " + movement);
    }
}
queen adder
cosmic dagger
queen adder
low path
#

If you have a variable in a script that has a gameobject OR component type, then Unity will let you drag a prefab with that component on it to the component type.

#

Then that component variable effectively has a reference to your prefab although what it really has is a reference to the specified component on your prefab.

queen adder
#

All right, thank you so much

cosmic dagger
#

a script attached to a GameObject is a Component. a Component is a Type. if the GameObject has a component matching the variable type of a script, you can drag it as a reference into that variable slot . . .

queen adder
#

thank you for everything and I'm sorry if i bothered with my question but I'm new at this. So it's hard for me the understand the all concept

cosmic dagger
#

not a problem, good luck!

hot wave
#
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            //See where a ray from mouse position hits our invisible lever plane, and have lever look at that point
            if (Physics.Raycast(ray, out hit, 10, leverPlaneMask))
            {
                Vector3 lookPosition = hit.point - transform.position;
                lookPosition.z = 0; //We can zero out one of the axis because the lever cannot move in all 3 axis
                
                Quaternion lookRotation = Quaternion.LookRotation(lookPosition);
                transform.rotation = lookRotation;
            }
        }``` how to clamp? I know I should put xrotation on x so it knows where to clamp, but where is x?
#

I want to learn how to break this down so i can adjust, if ok, can you help me understand what is happening in the computations

I am trying lookPosition.x = Mathf.Clamp(lookPosition, -90f, 90f); but it doesnt work

dark prism
#

Hi guys how would i get an object to spawn in front of another object when its enabled? in my case i have coins spawning every so offten randomly. and i want a cloud to cover them when they are enabled? my game is 2D

thorn holly
#

I’m a little confused about what you’re trying to do. Should there be one cloud per coin?

dark prism
#

yes

#

like one cloud for each coin that is spawned

swift crag
#

so you want to have a little "poof" as the coin spawns in

#

and then the poof goes away

dark prism
#

the reason in doing this is beacasue i have object pooling in my game. and if i was to spawn the cloud/ make it a child to the coin. it will get destroyed and not come back when enabled again if that makes sense

swift crag
#

Okay, so you'll want to spawn a cloud prefab in the coin's OnEnable method (or fetch one from another object pool)

dark prism
#

ill show you a clip of the game. so it make more sense. im just popping out now so ill send it in a second

summer wasp
#

how can i activate a particle system from a prefab with the script in another?

public GameObject prefabFogo;
ParticleSystem fogo;

void Start()
{
    rb = GetComponent<Rigidbody>();
    fogo = prefabFogo.GetComponent<ParticleSystem>();
    if (fogo != null)
    {
        Debug.Log("Particle System Found");
        fogo.Play();
    }

the debug log is appearing, but the particle is not playing

wintry quarry
#

prefabs don't exist in the scene

hot wave
#

I fixed the clamp UnityChanOkay

#

but transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 5.0f); is it ok to multiply time.deltatime to 5?

#

or no

#

I wanted to make it faster, but I might be making x5 more calls?'

wintry quarry
hot wave
wintry quarry
#

so it's kind of esoteric

hot wave
#

what is esoteric

wintry quarry
#

mysterious

#

not clearly defined

#

The third parameter in Slerp is supposed to be the percentage from A to B you want the result to be

#

but you're misusing Slerp (in a very common way) in a way that makes the units or meaning of that parameter very hard to define

hot wave
#
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            //See where a ray from mouse position hits our invisible lever plane, and have lever look at that point
            if (Physics.Raycast(ray, out hit, 10, leverPlaneMask))
            {
                Vector3 lookPosition = hit.point - transform.position;
                lookPosition.z = 0; //We can zero out one of the axis because the lever cannot move in all 3 axis
                //lookPosition.x = Mathf.Clamp(lookPosition, -90f, 90f);
                Quaternion lookRotation = Quaternion.LookRotation(lookPosition);
                if (Quaternion.Angle (lookRotation, baseRotation) <= maxAngle)
                {
                    targetRotation = lookRotation;
                }

                //transform.rotation = lookRotation;
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 5.0f);
                Debug.Log(hit.point);
                //transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * 5f);
            }
        }``` it is like this, but not sure if I did it right
#

but it works i think

#

also, i dont really know how to use it much since I am just starting, everything will be wrong, but I want to learn UnityChanOkay

wintry quarry
#

It will work it's just not easy to adjust or think about the speed in any sense

#

like it's not "meters per second", it's not going to swing the lever all the way in some defined number of seconds.

#

There's no concrete measurements to reason about - you just kind of adjust those numbers and see if it "feels" right

#

and it's also going to slightly have different behavior based on framerate. But it will generally feel "ok"

#

If you used for example Quaternion.RotateTowards(current, target, Time.deltaTime * 5f); then you could confidently say "the lever will rotate at 5 degrees per second"

#

Also Slerp used in this way will theoretically never completely reach the end state

hot wave
#

I also checked, it doesnt fully go to the end UnityChanThink

#

so first one is current and 2nd is target?

wintry quarry
#

for RotateTowards it's (current, target, speed)

#

for Slerp/Lerp it's supposed to be (start, end, percent)

#

but you're doing (current, end, some arbitrary number)

#

which gives a nice effect and is used commonly, it's just a little bit odd to work with

hot wave
#

ah I see I see UnityChanOkay, I never knew about RotateTowards

#

I think it is what I need

#

thank you praetor

dark prism
elder osprey
#

What is the point of multiplying by Time.fixedDeltaTime instead of 0.02?

wintry quarry
#

it's not always 0.02

#

that's just the default

shell sorrel
#

!ide

eternal falconBOT
polar acorn
elder osprey
wintry quarry
tall delta
wintry quarry
#

Sure but I want to point out in this case that's completely irrelevant and this used of fixedDeltaTime is merely a constant mul;tiplier into an awkward misuse of Lerp

tall delta
#

I totally agree, hence the preface of my message. but thought it might be helpful to know / understand why people and tutorials will keep telling you to use FixedDeltaTime when dealing with physics movement 😄

summer stump
#

It IS needed in NON-physics-based movement though

tall delta
rocky canyon
#

nah its not symantics.. if ur setting velocity directly in fixed update theres no need for scaling

summer stump
rocky canyon
#

ur just compressing the multiplier

#

leading to higher values to achieve the samething

#

if ur doing ur calculations in update then yea it might be necessary

#
    private void ApplyGravity()
    {
        Vector3 gravityForce = new Vector3(0f, -gravity, 0f) * rb.mass;
        Vector3 gravityAcceleration = gravityForce;
        rb.velocity += gravityAcceleration * Time.fixedDeltaTime; // this is when i'd use fixedDeltaTime
    }```
silk night
#

iirc velocity does not need timescaling

#

only if you change position directly

rocky canyon
#

anytime i do += or *= i include either Time.fixedDeltaTime or time.deltaTime depenind on where it is

silk night
#

cause position change is velocity * time

rocky canyon
#

b/c velocity only gets calculated during the fixed time step

#

if u were calculating the velocity in update.. w/o scaling that.. now that would be an issue i would assume

silk night
#

no velocity in general

rocky canyon
#

like custom calculations

silk night
#

no time scaling

summer stump
#

Velocity is in meters/second, so it is already scaled by time

#

Maybe I should have said physics ENGINE based earlier, and that would be clearer. Now that I think about it

rocky canyon
#

depends on where ur calculating that velocity

summer stump
#

Velocity and AddForce are handled by the physics engine directly

rocky canyon
#

physics are always fun 😄

#

im guilty of modifying the velocity.. i rarely use AddForce

#

never noticed an issue tho.. the engine pretty robust

summer stump
foggy crypt
#

Is there a way to change scene index?

rocky canyon
#

im not math savy enough to use AddForce

silk night
#

AddForce is basically just a utility function for changing the velocity 😄

summer stump
tall delta
# silk night iirc velocity does not need timescaling

multiplying by fixedDeltaTime is correct in that example, when manipulating rb.velocity. what's not correct is multiplying by rb.mass. since in this context we're getting the acceleration of gravity, not the force.

rocky canyon
#

or atleast for me it is

silk night
rocky canyon
#

i know its simple.. but sometimes i get hung up on it

foggy crypt
summer stump
rocky canyon
#

drag and drop

tight fiber
#

Hi, I'm new to Unity and I would like to know what you would recommend to me to progress quickly (tutorial, project, etc.) for my final project, a multiplayer card game.

rocky canyon
#

say i want something to move X meters per second

        float requiredForce = rb.mass * targetSpeed / Time.fixedDeltaTime;
        rb.AddForce(transform.forward * requiredForce, ForceMode.Force);```
wouldn't this be the right way to do that?
eternal falconBOT
#

:teacher: Unity Learn ↗

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

silk night
rocky canyon
#

start simple.. do something, build on that something.. rinse and repeat

wintry quarry
#

of course you can also just do rb.velocity = desiredVelocity;

rocky canyon
#

i wish i'd payed more attention in school

tight fiber
#

thx

rocky canyon
silk night
#

if you want a fixed speed no

#

if you want to calculate how hard an object bouncing into yours affects the speed then yes

wintry quarry
rocky canyon
#

okay cool.. i need to start doing stuff like this.. w/ math in mind.. soo far in physics i just tinker and change values until i get wat i want..

#

thats not the proper way to really learn anything

tall delta
#

rb.velocity = transform.forward * targetSpeed; would also do the trick

rocky canyon
#

what math subject do physics calulations fall under? in school i took Physics 1 and 2 but isn't it included in some other branch of math?

#

calculus maybe?

silk night
#

isnt that algebra? not sure tbh

rocky canyon
#

yea, u may be right.

#

all i remember in physics we had these "train problems" and it would take a whole 2 pages of college ruled worth of work..

#

(you had to show u work or u'd flunk)

wintry quarry
#

vector arithmetic?

rocky canyon
#

a train leaves station a, heading towards station b at 10:00 travelling..

#

that type of junk ☝️ lol

wintry quarry
#

that would be algebra but depending on the nature of the equation that results you might need calculus to solve it

rocky canyon
#

alrighty.. sounds legit. i need a refresher on that stuff for sure imma go hunt down some tutor type sites and see how rusty i am

tall delta
rocky canyon
#

all the exam questions i can remember all involved cars, trains, planes, rockets, and balls

#

not sure where to find a sk at..

cinder crag
#

im having a bit of a problem , i dont really know how i can make a smooth dash ability like daves dash tutorial since im using a character controller and he uses a rigidbody , how can i make it like his but character controller?

https://youtu.be/QRYGrCWumFw?si=xWCav_H03XuECfVw

FULL 3D DASH ABILITY in 11 MINUTES - Unity Tutorial

In this video I'm going to show you how to code a full 3D Dash ability in Unity. Including dashing in multiple directions based on player input, keeping the momentum after dashing and adding camera effects to make the dash feel more alive.

If this tutorial has helped you in any way, I would r...

▶ Play video
rocky canyon
#

just like ur doing there.. all u need to do is flip that canDash bool to true... and set it back to false in the coroutine

worthy merlin
#

Was watching a video that was telling people to use [SerializeField] instead of public to declare variables. Is there a reason behind this preference?

rocky canyon
#

yes, w/ serializedfield u can keep the variable private

#

private is better than public..

#

less chance to f*ck up ur code

modest dust
#

In most cases you need close to none public fields

rocky canyon
#

only use public variables when u need access to them outside the class theyre within

worthy merlin
#

ah

cinder crag
worthy merlin
rocky canyon
rocky canyon
#

ignore the [ReadOnly] thats something else

rocky canyon
tall delta
# cinder crag im having a bit of a problem , i dont really know how i can make a smooth dash a...

sound to me like you just want the movement to be a bit smoother, I think an animation curve is the easies thing to use here.

    public float dashDuration = 5.0f;
    public float dashSpeed = 10.0f;
    public AnimationCurve accelerationCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));

    IEnumerator Dash()
    {
        float elapsedTime = 0.0f;

        while (elapsedTime < dashDuration)
        {
            float normalizedTime = elapsedTime / dashDuration;
            float speedMultiplier = accelerationCurve.Evaluate(normalizedTime);
            transform.Translate(Vector3.forward * dashSpeed * speedMultiplier * Time.deltaTime, Space.World);
            elapsedTime += Time.deltaTime;
            yield return null;
        }
    }

then you change the accelerationCurve in the editor to match the 'smoothness' you want

elder osprey
elder osprey
rocky canyon
#

this is how i did it.. (for input I just set isDashing to true) then the coroutine sets it back to false..

#

the dash vector is just added into the Move function.. and at the end of it im slowly lerping it back to zero..

#

so when i hit the button it adds the dash value i have assigned.. and then it takes care of itself..

cinder crag
cinder crag
rocky canyon
#

a pirate game i abandoned @cinder crag

#

you can see the dash towards the end (its a little subtle) but i didnt want it to be a big dash

cinder crag
cinder crag
rocky canyon
#

yessir lmao

#

thx

cinder crag
#

Npnp

rocky canyon
#

i might return to it sometime

cinder crag
#

Would be cool if you finish it ,

rocky canyon
#

i bit off more than i can chew

tall delta
rocky canyon
#

scoped too big

rocky canyon
rocky canyon
#

lol BOOM

#

oh i forgot dash += Camera.main.transform.forward * (playerSettings.dashForce * 1f); i do this when i get the input for dash... then the move function calls the coroutine because the dash force is now greater than the magnitude i assigned cs if (dash.magnitude > dashMagnitude) { finalVelocity += dash; StartCoroutine(Dash()); }

#

i wrote it a long time ago.. sooo its not the best code tbh
but it works..

golden ermine
#

Hi I have this code that I assign to gameobject which I then put on my two buttons, one is SAVE and one is LOAD. When I click SAVE it will save my data(player and cam position and amount of deaths) and when I click LOAD it will load all that data. Problem is that I have SAVE and LOAD button in my game scene and I want SAVE button in my game scene and LOAD button in my main menu scene but then I dont know how can I implement same method to just load game data and load game scene.

cinder crag
wintry quarry
golden ermine
#

but also my SaveServiceSystem script is on gameobject inside game scene and menumanager is in main menu scene

wintry quarry
#

Which is only one part of making a DDOL singleton

wintry quarry
#

and enforce its singletonness

golden ermine
#

which method is easier

rancid tinsel
#

is there a quick way to make this change the instance of the script rather than the script itself?

rancid tinsel
wintry quarry
polar acorn
golden ermine
rancid tinsel
#

oh nvm

#

i thought it was changing it for all of them but it isnt changing it for any lol

#

mb

#

turns out im an idiot and forgot to actually use the function anywhere

wintry quarry
golden ermine
#

like this?

wintry quarry
#

no

#

that doesn't enforce it being a singleton, nor does it assign the instance property anywhere.

#

just look up Unity DDOL singleton for examples

rancid tinsel
#

if im not crazy, at 2 base attack speed this should give 0.4 attack speed at first and then 0.8 attack speed after right? making it 3.2?

golden ermine
gilded verge
#

ok so im trying to make an fps i managed to make a camera that renders the world and another that renders the weapons. how do i render the weapon cam on top of the world cam?

wintry quarry
golden ermine
#

Will that work like that or should I add something more so it becomes ddol singleton

wintry quarry
polar acorn
rancid tinsel
golden ermine
#

And I still dont understand how will I get that data saved from my game scene and when I again start to play game and im in main menu, then I click load game how will it load my data that was saved when I clicked on save button

rancid tinsel
#

i was increasing the upgradeCount before calling the function

foggy crypt
#

Hello
object.DontDestroyOnLoad for some reason creates a copy of an object it is refered to everytime a different scene loads:

void Update()
{
    Object.DontDestroyOnLoad(this);
}
wintry quarry
golden ermine
#

what is POCO?

wintry quarry
#

i.e:

  • Press load in main menu to call the load function
  • Load simply loads the data into a plain object and stores it on the save amanger
  • You load the game scene
  • Game scene script reads the loaded data from the save manager
#

plain old C# object

wintry quarry
foggy crypt
wintry quarry