#💻┃code-beginner

1 messages · Page 188 of 1

ripe kayak
#

so basically what im tryng to do is make a pop up when i press exit

slender nymph
#

we are aware of what you are trying to do

#

your issue is that you are trying to use a variable that does not exist

ripe kayak
polar acorn
#
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 143
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-2-08
slender nymph
#

surely you know what a variable is, right?

swift crag
#

if the variable is named quitPanel, you can't write QuitPanel or QUITPANEL or quitpanel or florp

swift crag
#

the only valid way to reference that variable is quitPanel

slender nymph
slender nymph
polar acorn
#

They named it something completely different

ripe kayak
#

i have no idea

slender nymph
#

okay it's clear you have no clue what you are doing. so stop, and go do some beginner courses to learn c#. there are some great ones pinned in this channel

polar acorn
ripe kayak
#

im simply watching tutorials

polar acorn
#

We cannot help you if you literally do not know what the words mean

polar acorn
rose galleon
#

Still working on that .-.

swift crag
#

Are you using multiple scenes for different areas in your game?

slender nymph
# ripe kayak btw i fixed the issue

if you go learn the basics you won't run into this issue again because you'll actually understand what you are doing therefore you will save yourself even more time over the course of developing your game

rose galleon
swift crag
#

Okay. I would suggest having a "game controller" object that lives in the DontDestroyOnLoad scene.

rose galleon
#

The gamecontroller is already DontDestroyOnLoad

swift crag
#

It should have a method to load a scene and position the player somewhere in that scene.

rose galleon
#

The controller and the Player are

ripe kayak
swift crag
#

You can write a coroutine that:

  • fades the screen to black
  • loads the new scene
  • positions the player
  • un-fades the screen
slender nymph
rose galleon
swift crag
#

Oh right, you've got the save data.

rose galleon
#

Yeah

spiral narwhal
#
itemBuilder?.Build();

'?.' on a type deriving from 'UnityEngine.Object' bypasses the lifetime check on the underlying Unity engine object

What does this warning mean? Is it possible to use it if you learn the side effects or is it rather a no-go

#

i.e. is start not called?

slender nymph
swift crag
swift crag
# rose galleon Yeah
    [System.Serializable]
    public class SaveData
    {
        public string sceneName;
        public Vector3 position;
    }

    IEnumerator LoadFromSave(SaveData data)
    {
        AsyncOperation handle = SceneManager.LoadSceneAsync(data.sceneName);

        yield return handle;

        Player.instance.transform.position = data.position;
    }
#

Could be as simple as this.

#

I would suggest making SaveData store all of the important information (e.g. upgrades, quest progress, etc.)

#

and then have a smaller class for where you should respawn at

rose galleon
swift crag
#

SavePointData, maybe

spiral narwhal
ripe kayak
#

i really apreciate u guys helping me out and im just chilling around, and im also learning btw i was joking

slender nymph
#

not possible

swift crag
#

The method runs until it hits a yield statement, then pauses.

ripe kayak
#

and for the emojis that's just me do that most of time

swift crag
#

If you pass an enumerator to StartCoroutine, Unity will ask it for a new value every frame (by default). This resumes the method until it hits another yield

#

But you can also yield special values to change that behavior. Notably, you can yield an AsyncOperation to make the coroutine wait until the operation is done

rose galleon
swift crag
#

It's not a unity object at all; there's no notion of being "destroyed"

open field
#

Object.GetComponent<Renderer>.material = white;

#

its gives an error

swift crag
#

You'd just need to store it somewhere that you can always access.

#

So, for example, I would hang on to the current save data in a static field (or put it in the singleton game controller)

open field
#

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

public class MonkeButton : MonoBehaviour
{
public GameObject Object;
public Material red;
public Material white;
public AudioSource sound;

void OnTriggerEnter()
{
    Object.GetComponent<Renderer>.material = red;
    sound.Play();
}
void OnTriggerExit()
{
    Object.GetComponent<Renderer>.material = white;
    sound.Stop();
}

} This is my full script

rose galleon
slender nymph
pastel patrol
#

I want to set the rb (rigidbody) to 0,0
please help

swift crag
open field
#

Assets\Scripts\MonkeButton.cs(14,16): error CS0119: 'GameObject.GetComponent<T>()' is a method, which is not valid in the given context

swift crag
#
public static class Whatever {
  public static SaveData someCoolData;
}
slender nymph
open field
#

this is the error

swift crag
#

Whatever.someCoolData holds a SaveData. Bam.

#

SaveData is not a unity object. It isn't instasntiated or destroyed.

open field
slender nymph
#

() is used to invoke a method

spiral narwhal
#
    [CreateAssetMenu(fileName = "ItemSO", menuName = "Tool", order = 0)]
    public class ToolSO : ItemSO
    {
        [SerializeField] private int _maxDurability;

        public int MaxDurability => _maxDurability;

        public int CurrentDurability { get; private set; }

        public override ItemSO Build()
        {
            return copy of this and:
            CurrentDurability = _maxDurability;
        }
    }

How would I do the pseudocode in Build() for a scriptable object?

open field
swift crag
#

It copies any unity object.

spiral narwhal
#

Okay thanks I'll try

rose galleon
open field
swift crag
#

and then you need to store it

slender nymph
swift crag
# spiral narwhal Okay thanks I'll try

I'm not a huge fan of storing mutable data in scriptable objects like this. Instantiating the object does create a fresh copy you can modify as you want, but...

polar acorn
swift crag
#

I prefer creating a separate class that references an ItemSO

swift crag
#
public class Tool : MonoBehaviour {
  public ToolSO toolData;
}

e.g.

polar acorn
rose galleon
swift crag
open field
#

Object.GetComponent<Renderer>.material = white; this is the line wher should i put the ()

slender nymph
#

read the error again

rose galleon
swift crag
#

If you want to store it inside a unity object, then yes, you need to make sure this object isn't destroyed (and that you always have a reference to it)

swift crag
spiral narwhal
open field
# slender nymph read the error again

Assets\Scripts\MonkeButton.cs(14,9): error CS1955: Non-invocable member 'MonkeButton.Object' cannot be used like a method.
then it gives me this error

slender nymph
#

you've put the () in the wrong place. the original error actually showed you where to put it

open field
#

Object().GetComponent<Renderer>.material = white;
sound.Stop(); i did it here

slender nymph
#

yeah that's clear from the error

#

your variable is not a method. you invoke a method

swift crag
# rose galleon A lot

The script is the text file that contains your C# code. In your case, it's going to define a single class called SaveData.

SaveData doesn't inherit from UnityEngine.Object, so it is not a unity object.

You can construct a SaveData like this:

SaveData myData = new SaveData();

You now have an instance of SaveData in a variable named myData. myData holds an object, and the type of the object is SaveData.

You need to store this object somewhere that you can always access. A great choice would be your game controller. Your game controller is a Unity object, and you put in the "dont' destroy on load" scene so that it doesn't die when you change scenes.

open field
#

Assets\Scripts\MonkeButton.cs(14,16): error CS0119: 'GameObject.GetComponent<T>()' is a method, which is not valid in the given context this is the old one what should i do

slender nymph
open field
#

(the old error)

slender nymph
#

please learn to read while you're at it

swift crag
#
public class GameController : MonoBehaviour {
  public SaveData currentSaveData = new();

  void Awake() {
    // consider loading a save file here.
    // otherwise, just put the default scene and position in!
  }
  
  public void UpdateSaveData(string sceneName, Vector3 position) {
    currentSaveData.scene = sceneName;
    currentSaveData.position = position;
  }
}
#

It might look like this.

slender nymph
#

why don't you read the error and find out?

polar acorn
#

To see where it expects parenthesis

open field
#

my english is 5% good idk what to say

slender nymph
#

you don't need to understand english to see where the () are in that error message

open field
#

just idk where to put it

slender nymph
rose galleon
rose galleon
summer stump
slender nymph
#

it's a good thing that their error message shows where to put the parentheses when calling GetComponent<T>()

rose galleon
slender nymph
#

your input was not needed here, nor were the pings

summer stump
#

Nor did it even help them... because it explained something different

frigid sequoia
#

Is there any reason why adding transformations constraints to a rb dissables the collisions with said object?

slender nymph
#

that shouldn't affect collisions like at all

#

is the issue that your collider is actually passing through an object it should collide with, or is it the physics messages like OnCollisionEnter not being called?

grand hare
#

where do I map my uv points on my plane mesh? do I map them on every vertex or what?

frigid sequoia
# slender nymph that shouldn't affect collisions like at all

Like I have this thingy am I want it to have a capsulle collider, and it needs a rb cause all enemies do, is to hanlde knockback and collisions with the proyectiles; but if I use the normal rb, the item gets pushed away form the floor due to the capsule collider, so I checked the freeze position boxes (cause it is turret and is not meant to move anyways) and then it just ignores all collisions with everyting

#

Like that shouldn't do that right?

slender nymph
frigid sequoia
#

Everything is ignored

#

Just phases through

slender nymph
#

did you make the object kinematic

#

actually show the objects that should be colliding at runtime

frigid sequoia
#

But does collide with the rbs though

slender nymph
#

right and that is why i asked since you aren't bothering to provide any actual details.

#

you need to show the objects or provide any useful details if you want to get help. i do not want to play 20 questions with you just to get some absolutely basic info

frigid sequoia
#

This with a non-trigger collider and non-kinematic rb

#

The player gets "gently" pushed out

slender nymph
#

typically when someone wants to see an object, they want to see the inspector

frigid sequoia
#

If I use kinematic, the player cannot phase through, but the proyectiles do

#

This is the inspector

#

I don't know what you want to see there since I am like literally changing it everty 2 mins so...

slender nymph
#

now show the projectile and the player

frigid sequoia
#

Player

#

Proyectile

slender nymph
#

the projectile is a trigger collider. it will phase through anything because it does not physically collide

#

as for the player, it probably depends on how you actually move it

frigid sequoia
#

As far as I know it does with OnTriggerEnter(); if the object has a rb that's it

#

This does work with objects with the same setup but unfreeze constraints

slender nymph
#

the constraints have nothing at all to do with trigger messages. it just prevents physics from moving the objects on those axes. first you need to ensure you are receiving a physics message
then you need to make sure that your logic is correct. for example, why are you checking for a specific layer there? why not check for a tag or a component instead

frigid sequoia
#

I think it was to work with raycasts

slender nymph
#

also what object is that component even attached to. it seems like it should be attached to the turret, but your previous screenshot did not include anything other than the collider and RB

frigid sequoia
slender nymph
#

your turret does not

#

also how are you even assigning the enemyCollisionLayer? because it isn't visible in the inspector

frigid sequoia
frigid sequoia
slender nymph
#

show how you assign that

late bobcat
late bobcat
#

ye it is

slender nymph
#

are you certain you don't have any code on the prefab causing it to disable?

rare basin
#

btw, perfect use case for a dictionary

    [SerializeField] private float purpleGemChance = 0.05f;
    [SerializeField] private float redGemChance = 0.1f;
    [SerializeField] private float blueGemChance = 0.3f;
    [SerializeField] private float greenGemChance = 0.4f;
slender nymph
#

perhaps in Start?

polar acorn
#

Show code for Orbit

slender nymph
#

we are seeing the code for Orbit lol

#

they disable it in Start

late bobcat
#

ye

polar acorn
#

Oh

rare basin
#

gameObject.SetActive(false);

polar acorn
#

I didn't see the class name, I thought we were looking at something else

#

Yeah that'll do it

late bobcat
#

okay so that's what's setting it to unactive

frigid sequoia
#

It does work, I assure you of that, is working for other objects

slender nymph
#

prove it. put some logs in OnTriggerEnter and log what is being hit and its layer

late bobcat
#

actually not it should one for each gem

frigid sequoia
#

It does work with anything on the Layer, doesn't need the enemyscript

slender nymph
#

with the turret . . .

tame obsidian
#

hi, let me ask you something. when we make a multiplier game on this steam, we make the server that creates the lobby. can we make this a steam server server, so no one in the lobby will be a server.

wintry quarry
slender nymph
frigid sequoia
#

Should check that

frigid sequoia
swift crag
#

A serialized field is stored in the prefab/scene

#

Unity remembers its value for each instance of the component.

#

[HideInInspector] just stops the field from appearing in the inspector. It can still be serialized.

wintry quarry
swift crag
#

So if you change = 6 to = 5, all of the existing instances of the component will still have a 6 in that field

#

the field initializer is overwritten by the serialized value if one exists

wintry quarry
#

Not only that, because it's hidden in the inspector, you have no way to change it back

#

unless you change it in code

frigid sequoia
#

So, since I am not changing it at all it should be NonSerialized?

wintry quarry
#

but then you might as well just not serialize it at all

swift crag
#

Do you need a unique value to be remembered for each instance?

#

If not, make it non serialized

frigid sequoia
#

No, the layers are gonna remain the same all the time

wintry quarry
polar acorn
#

Or just, like, use private

#

why is it public at all

frigid sequoia
spiral narwhal
#
if (inventorySlot?.Item is not ToolSO tool) return;

If inventorySlot is null, will this return?

frigid sequoia
#

Though could be just protected

polar acorn
swift crag
#

a destroyed unity object compares equal to null

rich adder
swift crag
#

but it's not actually null

wintry quarry
#

is not returns true for null

swift crag
#

Ah, but inventorySlot is a plain old class, isn't it?

#

So that's okay, nevermind.

spiral narwhal
#

This is not a MonoBehaviour

swift crag
#

(or plain old record)

frigid sequoia
#

So like that is the optimal way then?

rich adder
#

ohh

slender nymph
spiral narwhal
#

It's not a ScriptableObject either

#

It's just a class

#

A C# class with no inheriting classes

green island
#

i need to be able to get collisions on an gamobject but i want to still be able to pass through the gamobject but when i set istrigger to true it doesnt get the collision and if its falls u cant walk through it

rocky canyon
#

istrigger works fine, but u must have a rigidbody.. preferably on the other object..
or to prevent it from falling you can lock the constraints (x,y,z) axis

open kernel
#

hi, don`t know where to ask this but how can I make a transparent img object? So an object thats just a png without background

timber tide
#

in the import settings when you select the object there's options for how to use alpha values

green island
rocky canyon
#

OnCollision would work if u turn off isTrigger

honest haven
#
        {
            Debug.Log(hit);
            Vector3 newPosition = new Vector3(
                Mathf.RoundToInt(hit.point.x) != 0 ? Mathf.Round(hit.point.x / 2) * 2 : 2,
                Mathf.RoundToInt(hit.point.y) != 0 ? Mathf.Round(hit.point.y / 2) * 0 : 0,
                Mathf.RoundToInt(hit.point.z) != 0 ? Mathf.Round(hit.point.z / 2) * 2 : 2);

            floorBuild.position = newPosition;
            
            if (Input.GetMouseButtonDown(0))
            {
                Instantiate(floorPrefab, newPosition, floorBuild.rotation);
            }
        }``` i have to press mouse 0 like upto 5 times to register. is et mouse button down correct
timid saffron
#

where did i go wrong

timber tide
rich adder
rich adder
#

its pretty big syntax error

green island
timber tide
#

or use alpha clipping on opaque shaders

rocky canyon
#
            if (Input.GetMouseButtonDown(0))
            {
                // now raycast
                Instantiate(floorPrefab, newPosition, floorBuild.rotation);
            }
        }```
honest haven
timid saffron
rich adder
rocky canyon
honest haven
rocky canyon
#

but a trigger is what u want.. your setup is just wrong apparently

timid saffron
green island
timid saffron
#

this doesnt work though

#

it wont switch cameras

rocky canyon
#

put the OnTriggerCode on the thing with the trigger collider

rich adder
rocky canyon
timid saffron
honest haven
# timid saffron

if(person.enabled) that is checking if true. if(!person.enable) that is checking for false.

rocky canyon
green island
rocky canyon
#

show the code, and a screenshot of the object / trigger/ and its inspector

rich adder
timid saffron
#

i have keyboard

sour willow
#

in mac, i do not have snippets for alot of functions can anyone help?

timid saffron
#

wait okay. i didnt know what keypad was my bad

sour willow
#

i have downloaded the snippet extensions

timid saffron
#

i saw key and thought keyboard

rocky canyon
#

theres two different enter keys

rocky canyon
#

show the heirarchy and the sceneview

green island
orchid trout
#

What is the correct way to make unity allow me to delete/remove/whatever, completely remove a gameobject from the scene in edit mode?
I keep running into errors where it keeps telling me thats not how to delete a thing, but it wont tell me how to delete a thing

#

DestroyImmediate doesn't work

#

"InvalidOperationException: Destroying the root game GameObject of a Prefab Asset is not permitted.
InitiativeTracker.ClearInitiative () (at Assets/Scripts/UI/Initiative/InitiativeTracker.cs:147)"

rocky canyon
orchid trout
#

The result I want is the result you get from selecting it and hitting the delete key

rocky canyon
#

i dont see the collider in teh screenshot.. its size is .2 i wonder if its too small.. or underground or something

green island
rocky canyon
#

make it wider

rich adder
rocky canyon
#

ur rigidbody has a collider.. so if the code is in the Goal Script it should detect it just fine

ripe kayak
green island
ripe kayak
#

WHARRA DO

#

ignore the top X one

rocky canyon
#

show the code for GoalScript

green island
short hazel
eternal falconBOT
rocky canyon
#

bro.. thats nots OnTriggerEnter

ripe kayak
timid saffron
#

im still trying though i think i will fix it

short hazel
rich adder
hexed terrace
rich adder
#

make sure its runninig

rocky canyon
#

i said that wayyy up here

#

Make sure to use the correct method.. if ur using IsTrigger.. you need OnTriggerEnter

#

OnCollision is just that.. like if the ball were to strike the box and roll backwards that would be OnCollisionEnter

green island
ripe kayak
green island
#

no ; after Wait_for_intro

#

and when you call the function the w must be uppercase

ripe kayak
#

there two of wait for intro

#

line 13 or 18

wintry quarry
#

you also spelled Start wrong

#

Look at any basic C# code example. You do not put ; after the parameter list for a function like you did on line 16.

ripe kayak
#

alr

sour willow
#

definitely learn a c# tutorial before starting unity

ripe kayak
#

im doing great so far

#

made a main menu

#

and intro (wip)

polar acorn
ripe kayak
#

and level with player and everything

polar acorn
#

There is no "close enough"

orchid trout
#

I found the problem, the problem is that my list of gameobjects is not a list of gameobjects

polar acorn
#

you have to spell the words right

ripe kayak
#

my eyes sometimes fail me

#

i will still try

#

done

#

yay

#

thx

honest haven
rocky canyon
honest haven
rich adder
#

debug your bool of raycast and see Why you need so many tries

covert glade
#

helllo is it better to code in vs 2022

#

or vsc?

hybrid sundial
#

I finished the first juniour programming lessons and the car game is cool, currently I planted the obstacles but I want to make it an infinate loop where it generates obstacles in random places, I don’t know where to start

slender nymph
covert glade
#

if yes thats where u start learning how to make infinite loops for generating obstacles

#

but how to code it? idk im still new i just know the idea

spiral narwhal
#
            var adjacentObjects = Physics2D.OverlapBoxAll(
                transform.position,
                new Vector2(1.1f, 1.1f),
                0f,
                _connectableLayers
            );

Why does this collect the game object itself? It has the same layer and is within the bounds, of course, but why would Unity include the calling object itself?

covert glade
#

is the method Awake same as the method Start?

wintry quarry
rich adder
#

they both run once, thats the only common thing

covert glade
#

for making components knowable by the script

#

do i use awake?

#

or start

wintry quarry
rich adder
#

either, but awake best for initialization

wintry quarry
#

For initializing things that depend on other objects already being initialized, use Start

spiral narwhal
#

So how would I filter it out?

foreach (var adjacentCollider in adjacentObjects)
                if (adjacentCollider.gameObject is gameObject) continue;

In this case gameObject does not seem to work in that context

rich adder
#

adjacentCollider.gameObject is gameObject ?

covert glade
#

a changing variable like int x

#

or something?

wintry quarry
wintry quarry
#

what are you changing it to?

rich adder
# covert glade like a variable?

say you load your ScoreScript score by PlayerPrefs in awake, then you have another script like UI to read the score, thats where you use Start
uiText.text = thecoreScript.Score.ToString() (simple example, obv you would use events :P)

wintry quarry
#

Are you changing it to something that depends on some other object being initialized?

covert glade
#

idk

#

as iam following a course

#

so im tryna learn anything that idk

honest haven
rich adder
#

I keep my inputs polling to Update

rich adder
covert glade
#

im tryna understand before i implement

#

and add stuff to figure out more stuff

timid saffron
rich adder
spiral narwhal
#
public class ConnectableObject : DestroyableObject
    {
        // Called when Instantiate is used to create this instance
        private void OnEnable()
        {
            ConnectToAdjacentObjects();
        }

        private void ConnectToAdjacentObjects()
        {
            Debug.Log(transform.position); // <--- very wrong output
        }

Can anyone tell me why the position is so incredibly wrong? In fact, if I instantiate multiple objects, they all have that strange position

timid saffron
#

also debug log wont show message

rich adder
rich adder
timid saffron
#

i actualy tried to put debug log everywhere but it wouldnt work so i asked chatgpt

slender nymph
rich adder
rich adder
#

in the script

#

show me the script on the gameobject

timid saffron
#

public Camera firstperson;
public Camera secondperson;

rich adder
timid saffron
#

this is for ship

#

main ship we control

rich adder
#

derp moment

spiral narwhal
timid saffron
rich adder
#

on the gameobject

slender nymph
rich adder
#

show where you put it on the gameobject @timid saffron

timid saffron
rich adder
rich adder
#

show that

covert glade
#

what does this give me an error?

rich adder
spiral narwhal
# slender nymph how should i know? you haven't shown how you specify the position when you spawn...
public void PlaceConnectableAt(ConnectableObject prefabToPlace, Vector2 position)
        {
            var copy = Instantiate(prefabToPlace, transform);
            copy.transform.position = new Vector3(
                Mathf.RoundToInt(position.x),
                Mathf.RoundToInt(position.y),
                10f
            );
        }

which in turn is called by

public void Interact(Vector3 mousePosition)
        {
            var playerPosition = PlayerMovement.Instance.FeetPosition;
            var roundedMousePosition =
                new Vector2(Mathf.RoundToInt(mousePosition.x), Mathf.RoundToInt(mousePosition.y));
            var distance = Mathf.RoundToInt(Vector2.Distance(
                roundedMousePosition,
                new Vector2(Mathf.RoundToInt(playerPosition.x), Mathf.RoundToInt(playerPosition.y))
            ));

            if (distance > _rangeInMeters) return;

            ObjectPlacer.Instance.PlaceConnectableAt(_prefabToPlace, roundedMousePosition);
        }

The position works absolutely as intended because I can see the objects rendered perfectly on screen, it's just the print statement that's off for some reason

covert glade
#

it says im using a vector2?

slender nymph
#

Rigidbody2D uses a Vector2 for velocity. it has no z axis

covert glade
#

so do i make z as 0?

rich adder
timid saffron
rich adder
#

its 2 floats

timid saffron
#

inpsector

wintry quarry
rich adder
timid saffron
wintry quarry
rich adder
#

Unity turns V2 into V3 and 0s out the Z but thats if its not 2D

slender nymph
timid saffron
#

@rich adderdid i send you what you wanted?

spiral narwhal
rich adder
#

you are trying to use something thats not assigned

#

the computer doesnt know which camera you want

slender nymph
#

don't make assumptions about what is or is not correct. it's obviously correct at the time you print the position. remember that OnEnable is called before Instantiate returns

#

so it's printing the position of the parent object because that is where the object is when OnEnable is called

timid saffron
#

damn cool. it works now

#

although i can only do it once ill work on it now

#

minor details i miss 😄

spiral narwhal
slender nymph
#

or you could just specify the position in the Instantiate call instead of on the line after

spiral narwhal
#

No, there is more that needs to be done on instantiation

#

I just left it out for simplicity here.

#

Thanks for the help :)

slender nymph
#

stop truncating your code when sharing it. jesus that's annoying. what if the issue was caused by something you left out?

#

"hey what's causing my issue?"
share the code
"here's only part of the code that i'm going to assume is the part that is at fault because i totally know what is causing it which is why i'm asking for help"

spiral narwhal
#

Yeah no. The log was literally the first thing of the method.

timid saffron
#

this is the code

#

im pretty sure it can be written better but

#

it works

slender nymph
#
if(Input.GetKeyDown(KeyCode.Return))
{
  firstperson.enabled = !firstperson.enabled;
  secondperson.enabled = !secondperson.enabled;
}

would work assuming they are in the correct state when you start

broken drift
#

can someone help what's causing this error? these are the codes

timid saffron
#

this makes a lot more sense

#

i gotta think outside the box sometime soon

polar acorn
slender nymph
modest dust
#

you're using that in your newHP setter

#

And dear god, it hurts my eyes to look at how you name these methods

slender nymph
#

yeah the _ prefix should be reserved for non-public fields. it should never be used on anything public or on methods ever

hallow gate
#

can someone help me with something

hallow gate
#

my character in unity wont move properly even tho i did exactly as said in the tutorial. he just starts to jitter and get stuck whenever i press wasd

broken drift
#

thanks for the help and advice (although i just barely understand what's causing it) also sorry for the naming lmao, im still new but ill fix it

eternal falconBOT
hallow gate
# slender nymph show relevant !code

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

public class Playerr : MonoBehaviour
{
public float moveSpeed;

public bool isMoving;

private Vector2 input; 

private void Update()
{
    if (!isMoving)
    {
        input.x = Input.GetAxis("Horizontal");
        input.y = Input.GetAxis("Vertical");

        if (input != Vector2.zero)
        {
            var targetPos = transform.position;
            targetPos.x += input.x;
            targetPos.y += input.y;

            StartCoroutine(Move(targetPos));
        }
    }
}

IEnumerator Move(Vector3 targetPos)
{
    while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
    {
        transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
        yield return null;
    }
    transform.position = targetPos;

    isMoving = false;
}

}

eternal falconBOT
modest dust
broken drift
modest dust
broken drift
slender nymph
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

slender nymph
slender nymph
#

please learn to read

polar acorn
broken drift
#

thanks a lot

modest dust
hallow gate
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Playerr : MonoBehaviour
{
    public float moveSpeed;

    public bool isMoving;

    private Vector2 input; 

    private void Update()
    {
        if (!isMoving)
        {
            input.x = Input.GetAxis("Horizontal");
            input.y = Input.GetAxis("Vertical");

            if (input != Vector2.zero)
            {
                var targetPos = transform.position;
                targetPos.x += input.x;
                targetPos.y += input.y;

                StartCoroutine(Move(targetPos));
            }
        }
    }

    IEnumerator Move(Vector3 targetPos)
    {
        while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
            yield return null;
        }
        transform.position = targetPos;

        isMoving = false;
    }
}
#

character wont move he just jitters

slender nymph
#

you never set isMoving to true so you start that coroutine every frame

wintry quarry
#

this is way overcomplicated

slender nymph
#

go back to the tutorial you copied that from and set isMoving to true in the same place the tutorial does

hallow gate
wintry quarry
#
    private void Update()
    {
        if (!isMoving)
        {
            input.x = Input.GetAxis("Horizontal");
            input.y = Input.GetAxis("Vertical");

            if (input != Vector2.zero)
            {
                var targetPos = transform.position;
                targetPos.x += input.x;
                targetPos.y += input.y;
            }
        }

        transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
    }```
There's absolutely no reason to use a coroutine here
polar acorn
wintry quarry
hallow gate
# polar acorn What tutorial is it

Please watch the video till the end, then do it yourself :D

Chapters:
00:00 - Intro
01:06 - Concept explanation
03:08 - Importing character sprite
06:05 - Creating the script file
09:00 - Coding the movement
25:35 - Testing the game

Links
Visual Studio Download: https://visualstudio.microsoft.com/downloads/
Character Sprite: https://github.co...

▶ Play video
slender nymph
#

holy hell they actually did copy the tutorial correctly ah looks like that isMoving bit was corrected after the part i saw

wintry quarry
#

you skipped the isMoving = true; line

#

so that broke it

wintry quarry
#

in the future, copy the code as it is in the tutorial

hallow gate
wintry quarry
#

This is the tutorial code

#

you didn't write this

hallow gate
#

ohhhh

#

ye mb

polar acorn
#
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 144
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-2-08
hallow gate
#

thanks tho

vast saffron
hallow gate
green copper
#

This function is always returning the number in the box as an argument instead of the selected index of the dropdown. The object in question is a TMP_Dropdown

polar acorn
polar acorn
vast saffron
short hazel
#

5 × 2 = Hello world ? I've been lied to all my life

vast saffron
green copper
#

the docs say it should pass the index value

green copper
#

ah, missed that message thanks

spiral narwhal
#
            var roundedPosition = new Vector3(
                Mathf.RoundToInt(position.x),
                Mathf.RoundToInt(position.y),
                10f
            );

            var placedObjectsAtPosition = Physics2D.Raycast(
                roundedPosition,
                Vector2.down,
                1f,
                _placableLayers
            );

            if (placedObjectsAtPosition.collider is null)
            {
                var copy = Instantiate(prefabToPlace, transform);
                copy.transform.position = roundedPosition;
                copy.AfterInstantiation();
            }
            else
            {
                Debug.Log("Already exists");
            }

Could someone help me with the raycast? I think some value is not what it should be because some tiles are incorrectly "found" and therefore the player can't place an object there.

wintry quarry
slender nymph
#

yeah that should just be an OverlapBox

spiral narwhal
#

To check if there already is a "farming field" where the user clicks

wintry quarry
#

I think it should just be... a position calculation followed by a Grid.WorldToCell()

slender nymph
#

or a CheckBox if none of the info about what is there is actually needed

wintry quarry
spiral narwhal
#

It's not actually a tile. Those are all sprites

wintry quarry
#

Raycast is for rays within the 2d world
GetRayIntersection is for this.

pseudo ermine
#

Hey, I am currently working on a scoreboard that should increase when winObjects tag is checked/found, it increases to one and stays at 1.

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

public class landmineCounter : MonoBehaviour
{

    public GameObject mineDefusedCounter;
    public Text DefusedCounterText;
    public float defusedScore = 0f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

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

        
    }

    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "WinObjects")
        {
            Debug.Log("Collision detected with WinObjects");
            defusedScore ++;
            Debug.Log("Score increased to: " + defusedScore);
            DefusedCounterText.text = "" + defusedScore;
        }
    }

}
spiral narwhal
#

So the mouse doesn't really play a role anymore

#

It should just check if in that position, there is a gameobject with the layer

wintry quarry
#

do this to get the right position, then round

#

Oh wait you're doing a raycast to see if there's an object there?

#

This is kinda... all backwards

#

You should have a grid

#

and look up the grid coordinates

wintry quarry
#

I.e. the objects places should be looked up in a 2D array or a Dictionary

#

using physics for this is going to cause a lot of issues, performance being one of them

spiral narwhal
#

Ah so a simple check if there is a sprite in the list with key [position]? Yes, that could work

timid saffron
#

how can float not contain a definition for x?

#

its right there

slender nymph
#

x is a completely separate variable that is not part of the float struct

#

you just happen to have a float called x

timid saffron
#

okay. I changed the name

green copper
#

I'd like to make it so when the player selects an option in one dropdown menu, two other dropdowns are set back to their default value. When I run this with the setAllDropDowns0(); enabled, on selecting an option the dropdown remains open and all options when selected remain selected until the entire dropdown has checkmarks

timid saffron
#

the reason i assigned a flot to x y z was because:

slender nymph
#

because, again, your variables that happen to be floats are not part of the float struct

timid saffron
slender nymph
#

start by learning the basics of c# before learning unity

timid saffron
#

🫡

smoky niche
#

Hey there, I'm making a 2D platformer and I made a custom collision detection script using raycasting. Now I'm wondering if I should set the speed of my character before or after my collision detection?

#

The code for adjusting the character's velocity to be more clear

polar acorn
noble summit
#

hello, i know the basics of c# and want to learn unity, should i start with the "junior programmer" course or something else?

slender nymph
#

start with the essentials pathway first then do the junior programmer pathway. essentials covers a lot of stuff for the editor and just game development in general

swift crag
#

It's also good to get some reinforcement.

buoyant knot
swift crag
#

Mastery comes through repetition!

smoky niche
buoyant knot
#

idk exactly what your goal is here. it sounds like you want to simulate the impulse of a rigidbody colliding with an object of infinite mass

smoky niche
#

Well I have collisions with raycasts. For example if I'm running right and hit a wall, it will detect the wall and place my character perfectly against that wall using the hit.distance of the ray.

buoyant knot
#

It might help to know how my physics engine handles it. My custom physics engine does the following:

  1. If object is in reference frame, Cast to try to translate, without modifying velocity.
  2. Based on velocity, calculate desired displacement for one step of simulation (of fixedDeltaTime)
  3. Cast to move by that vector, or until the first thing we hit. Whichever comes first. If we got a hit, update velocity based on the angle. Move object there.
  4. Collide and slide algorithm: Repeat step 3 with whatever remaining displacement, deflected along the surface normal we hit.
#

also, in 2D, if you have simple colliders, use Collider2D.Cast instead of Raycast. Collider2D.Cast is only slightly more expensive, but gives better info for moving the whole thing.

#

I can send code at some point, because this algorithm is complex because of the edge case where the tiny amount of accuracy in how much we move makes a big difference. But my computer is in the shop right now.

#

like, if your RaycastHit2D says to move by X, and you move by X, you’ll be in contact but not able to cast or something. There’s a correction factor so you move just enough to be in contact to trigger collision callbacks, far enough to cast again without just reading the same hit again

#

This is because Physics2D is based off of Box2D, which gives every polygon an edge radius (for math reasons), and this edge radius becomes extremely important when you want to move an object to be right in contact with another

smoky niche
#

Alright interesting. Seems a bit complex indeed haha, but I'll try some things out

#

I can also show you my code to see what should be changed

buoyant knot
#

As far as your original question goes, for modifying velocity, as long as you calculate initial desired displacement based off the previous velocity, it doesn’t really matter when you change velocity before or after. As long as you get everything in before anything that depends on velocity can access it (eg physics sim)

#

But you usually want to do it after you cast because you need the normal of the hit to modify the velocity

smoky niche
#

Alright sounds good

#

Thanks!

buoyant knot
#

sure. sorry this is very complex lol

smoky niche
#

Would it be better if I send it in DM or here?

buoyant knot
#

once my computer comes back from the shop in a few days, I can send you code that might aid you.

smoky niche
#

Awesome

buoyant knot
smoky niche
#

Alright I'll DM it

buoyant knot
#

i do warn that it gets complicated

smoky niche
#

I know, hopefully I can wrap my head around it

buoyant knot
# smoky niche I know, hopefully I can wrap my head around it

This might give some guidance. This code will not be complete to copy for 2D because of the edge radius thing, but it gives the initial idea:
https://youtu.be/YR6Q7dUz2uk?si=6Oti9sTNvVHU7dli

How to make actually decent collision for your custom character controller. Hopefully you find this helpful and people will finally stop saying "jUsT uSe DyNaMiC rIgIdBoDy!!!1!!11!!"

Chapters:
00:00 - Intro
01:09 - Algorithm
05:11 - Implementation

Improved Collision detection and Response (Fauerby Paper):
https://www.peroxide.dk/papers/collisi...

▶ Play video
vast vessel
#

to get a random element from an array, do i need to do myArray[Random. Range(0, myArray, Length)]; or myArray[Random. Range(0, myArray, Length-1)];?
most resources online dont subtract one from the array length, but it dosnt make any sence to me, since the index of the last item should be one less than then the length of the array

rare basin
#

Random.Range for ints is exclusive

#

(0,5) for example will generate from possible numbers: 0,1,2,3,4

#

so you don't substract -1

vast vessel
#

thanks

small dagger
#

is there a way to see the type of a component in the editor?

rare basin
#

wdym

#

type of a component?

small dagger
#

I am using a VFX component and I want to reference it in code, but I'm not sure what data type to reference it by

#

like when I do GameObject.GetComponent<T>(), I'm not sure what the T is supposed to be

short hazel
#

Usually searching for

unity [your component name] scripting api
In your search engine will show a link where you can see what type it is, and which namespace it's in

#

Example for "particle system"
It's class ParticleSystem, and you need using UnityEngine to reference it

small dagger
#

ah ok thanks, I think I found it, I was looking for visualEffectAsset I think

#

I think a quicker way to do it than just googling it i s clicking the little question a mark icon in the editor, that opens the API on that component directly

rotund quest
#

hi

#

when i tried to switch my project platform from windows to android the sprites started to look weird, does anyone know why?

swift crag
#

The choice of platform is probably affecting how the textures get compressed

scarlet hamlet
#

Hi there 🙂 Would anyone happen to know if it's possible to have a nested class utilise [ExecuteInEditMode]?
I basically have a class with some logic being done on Update() in the Unity Editor, but when I nest this class in another script, it stops executing in Edit Mode

slender nymph
#

ExecuteInEditMode will not affect NestedUpdater because it does not inherit from MonoBehaviour so there's nothing to execute during edit mode. You could have the ParentClass component execute in edit mode and call NestedUpdater's Update method though

scarlet hamlet
#

Aah that makes a lot of sense, thank you 🙂

opaque mortar
#

can you suggest a vid for makeing guns

eternal needle
vapid mesa
#

hi i do this for animation switching but it don't work

opaque mortar
slender nymph
# vapid mesa

keep in mind that GetKeyDown is only true for the first frame the key is held down. so the next frame, if this code executes it will set the Speed parameter back to 0

vapid mesa
#

what can i do to fix it ??

polar acorn
# vapid mesa

Gonna be awfully hard to notice a change in the animation that's 1 frame long

polar acorn
cunning rapids
#

Yo can anyone help me in #archived-urp ? I have a massive issue with my camera but this channel is more active and I can't post non-code-related things here. It's late where I live and I need help

cunning rapids
#

How is this crossposting if I'm not sneding any unrelated stuff here?

#

I'm just asking for more help

#

Last anyone even touched the URP channel was like 4 days

slender nymph
#

you're literally posting in another channel to get help in the channel you posted your question in. that is considered crossposting and you are posting off topic since it is not code related

vapid mesa
cunning rapids
#

I guess I can wait

opaque mortar
#

well in say gun more like a hand that tags peple and has a cool dow

vapid mesa
#

the animation change only if it's finish you know if we can "break" an animation

polar acorn
vapid mesa
#

thanks it work

#

i was trying to make this animation since one month

swift crag
#

the exit time is when the transition is actually allowed to happen

#

if you have no exit time, you must have at least transition condition (or else you'd always instantly leave the state)

polar acorn
twin bison
#

is it normal on a project with about 10 scripts that every time i make a tiny change on a script i have to wait almost a minute to finally can click on the play button?

rare basin
#

it depends on your PC specs

charred spoke
twin bison
#

I don't get it why it's so extremely slow.

polar acorn
#

Remember that unless you're using assembly definitions it's recompiling every script. Including ones in any assets you have imported

twin bison
twin bison
rare basin
#

any assets imported

#

to the project?

#

that might be "Heavy"?

twin bison
#

what troubleshoot steps can i take? I was installing a uncompatible shader a few days ago, which i uninstalled becaues it was for URP

rare basin
#

close the project

#

delete your Library folder

#

and re-open it

twin bison
#

ok I will try 🙂 thx

sharp bloom
#

Hi, I'm trying to modify the colorSeed variable from code to get a random color for certain objects as they're spawned. This does not work, what I am doing wrong here?

twin bison
rare basin
#

you dont have .gitignore for your Library folder?

polar acorn
rare basin
#

true lol my brain is washed

#

don't know why i thought about git changes

twin bison
polar acorn
sharp bloom
#

Yes, it does nothing. I seems to not access the _colorSeed at all.

polar acorn
sharp bloom
#

Ah, I read that wrong. Changing the colorseed from the inspector works

#

But it changes the color for all of the objects

#

Which is not what I want, I want several objects with slight variation in color

polar acorn
#

I'm not sure how material property blocks work to be honest, but maybe you just need to do renderer.material.setColor? Accessing it will allocate a new material instance which is a bit of a performance hit but that's what you want to be happening anyway since each one should have a different material, right?

rare basin
#

because you are changing it

#

to the original material, which changes it to all objects that has that material assigned

#

you need to work on a material instance instead

twin bison
#

thank you very much

rare basin
sharp bloom
#

Even if I do this, the colorSeed variable still doesn't change in the inspector

polar acorn
green copper
#

is there a way to make a sprite fit with letterboxing/margin instead of stretch or tile?

sharp bloom
#

Removing the underscore does nothing either

polar acorn
#

If nothing logs, then the code simply isn't running.

sharp bloom
#

Imma see myself out

#

I had just disabled the script from inspector

polar acorn
#

🦆

trim gulch
#

Hello! I need some help
I'm working (for the first time) with a State Manager and States for my objects, and one of them is a gun
Say I have an "Inactive state script" for the gun where the player can't fire it, and an "active state script" where he can. So in the active, I want to give it a prefab of a bullet so it can instantiate it to shoot. However, as only my state manager script is actually atacched to the object, I don't know how to do it because I can't link it in the inspector. What can I do?

eternal needle
trim gulch
#

The Object only has attached this script

#

The script calls classes from others scripts that are the states

queen adder
#

i need help. So basically im groundchecking using a layermask array, however i dont know how to set the value of any point in the array. it hard to explain so ill try make is sound easier. my public layermask has two values and for the groundcheck i put layerMask[] but it needs a value inside the square brackets

trim gulch
#

However if I were to write a variable in the scripts for the states (which are separate) it wouldn't show up on the inspector

summer stump
polar acorn
queen adder
#

bc i have two different layers

polar acorn
queen adder
#

one is ignored by player

#

nono wait

polar acorn
#

Okay, so they are used in different cases, it's not just a mask that multiple layers are in?

summer stump
eternal needle
polar acorn
#

If that's the case, and it's just two masks with different uses, I'd just make two fields with descriptive names

polar acorn
#

It'd be different if they were supposed to be used in the same place right after each other but it seems like you're going to be using these in different places

dire tartan
#

im trying to make a button which interacts with physics eg if you throw a box on it or stand on it it pushes down how would i go about doing that?

eternal needle
dire tartan
#

i suppose setting it up

#

i have an idea of how to do it just not familiar with unitys functions

#

like if i want it to have resistence for example so an object has to be enough weight

eternal needle
dire tartan
#

okay thank you

#

i normally just look for tutorials so i can get an understanding of how to go about it but i couldnt find one for what i was looking for

#

and for the button to go up and down would i use an animation and swap between the two when something is on it?

eternal needle
#

Only thing I'd suggest on top of all the obvious stuff is add a timer and a counter. The timer so it does not constantly go between Enter and Exit. And counter so it does not "enter" multiple times

eternal needle
dire tartan
#

okay i see

#

thanks for the help

queen adder
#

BASICALLY IF U PUT A WHILE COMMAND IN THE WRONG PLACE AND PLAYTEST THE CODE COULD TRY RUNNING FOREVER AND U CAN'T STOP IT WHAT DO I DO I HAVENT SAVED IN 4 HOURS

swift crag
#

save more often and turn off caps lock

#

killing the editor won't make you lose any of your script files

#

just scene data that you haven't saved

queen adder
#

yh ive been mapbuilding

queen adder
#

is there a way to kill playtest

#

oh thx

#

is it outdated?

polar acorn
#

A bit but it still works

#

Some of the names are probably different now

#

but there's still a temp scene you can rename to .unity to restore the scene

queen adder
#

this one?

polar acorn
#

That is probably where I would look for backup scenes yes

queen adder
#

tysm one more thing tho

#

basically i want it so my camera plays different music depending on y level; the problem is how do i play it after the musics changed bc i cant put it in the if statement bc it restarts the song every frame

polar acorn
#

Check if it's not playing before playing anything

queen adder
#

how do i do that

dire tartan
#

how do i have an animation play and stay in the final frame of the animation instead of looping

teal viper
autumn tusk
#

unity is messing me up

#

making a script to disable camera rotation, did this by making a continously updating script that sets the camera z transform rotation to 0 but unity is being very confusing with quaternions

polar acorn
# autumn tusk

What are you trying to pull with (Quaternion.identity,0f)

autumn tusk
#

and i have the camera parented to the player character

#

so when i move it spins the camera as well as the player

#

i need to freeze the camera's z rotation

polar acorn
#

The solution to this is just don't have the camera be a child of the player

timid saffron
# autumn tusk

im also looking into this stuff lately. please ping me if you find a solution

autumn tusk
teal viper
polar acorn
#

Or just use Cinemachine and be done with it

teal viper
#

Is it a tuple..? Rotation doesn't take a tuple

timid saffron
timid saffron
teal viper
polar acorn
#

I think that particular error was solved a while ago

#

but both of you should just be using Cinemachine for camera following

timid saffron
timid saffron
#

i used that iin2d works well

timid saffron
rotund hull
#

!code

eternal falconBOT
rotund hull
polar acorn
rotund hull
#

ok

ivory bobcat
little cradle
#

how can I make a switch that only executes the code once?

        switch (playerState){
            case IDLE : {
                //PlayAnimation(client.player, idle, false);
                client.player.sendMessage(Text.literal("idle"));
                break;
            }
            case WALK :{
                //PlayAnimation(client.player, walk, false);
                client.player.sendMessage(Text.literal("walk"));
                break;
            }
      }

I got this lil code, and I can't figure out how to do it :(

#

mmm I got it in an update method

#

I think I can fix it by "using" the switch every time a change is done rather than leaving it on update method

#

but either way, it'd surely help me get better at coding, how could I go about it even if the switch is on update?

polar acorn
#

Update runs every frame

teal viper
little cradle
teal viper
gritty notch
#

does anyone know how i can make a loading bar for a method? i have a method that generates terrain, i want a loading bar that corresponds with the progress of that.

random patrol
#

Async in Unity runs on the main thread, and I am assuming there would have to be more logic behind it so it doesn’t lock until it is complete. Something like do X calculations then pause and update the progress bar.

north kiln
#

Async runs wherever you tell it to run, and yields however the function yields

#

there is no magic

ivory bobcat
# random patrol Async in Unity runs on the main thread, and I am assuming there would have to be...

Consider using tasks if you need multithreading else async would occur on the thread that it's started - you'd just be able to run asynchronous statements.
https://medium.com/@sonusprocks/async-await-in-c-unity-explained-in-easy-words-571ebb6a9369
https://simsekahmett.medium.com/multithreading-vs-asynchronous-programming-in-net-core-1f1380c4946f
A coroutine could suffice but I'm guessing you've likely already considered that.

north kiln
#

Yes, you would generally want to have the work broken down so you can send a callback to the UI

random patrol
north kiln
#

You can still do Task.Run to start a threaded task, you can still switch tasks to other threads

random patrol
#

Pretty sure last time I looked into it it doesn’t, but that was a while ago

rose galleon
#

how do I use transform.position to make one object go to the position of the other one?
For example: I have a Vector3 stored in TPLocation, and I want to make PlayerLocation go to the TPLocation

teal viper
random patrol
random patrol
north kiln
rose galleon
random patrol
#

Just do .transform to get the transform from a GameObject

rose galleon
random patrol
north kiln
#

Afaik in "normal" C# it works the same, if you "just use async" it will continue running on the same thread it was called from

#

so I'm not sure where this person's assumptions have come from

copper perch
#

What I am trying to do:

I have an FPS gun called the Twin Turbos, the Twin Turbos appear in the weapon Holder in each unity scene with the Unity Starter Assets FPS Controller.
I am trying to make the Twin Turbos fire and getting a sprite fire button to work with the gun firing animation in sync.
I want to be able to move while firing.
I am going to send you some scripts that were on the Twin Turbos the way it worked before was the old way in these scripts.

Before the firing button was not working properly, like I could only move and fire at the same time if I presses, and hold the sprite button and move, and if I move and then press the fire button the gun does not fire.
So, can you help me make the Twin Turbos fire while moving? I think the ray cast is done in the scripts I am going to send to you.

#

The reload that works with these Twin Turbos guns uses a On Click Function.
So, the way I imagine it is, if the player presses the fire button while moving the twin turbos will fire over and over again, so the Twin turbos shoot Animation is playing over and over in the Animation.
If the player presses the fire button for less than a second, at least the Twin Turbo Animation will play at least once (like the left Twin turbos pistol fires and then the right Twin Turbos pistol fires once)
Can someone help me do this on discord screenshare.
Currently the Twin turbos are not firing.
I have tried studying keywords, and functions in C# but no luck.

Using Paste.orCode.org I can send you the whole script easily below.

https://paste.ofcode.org/yUXHvpwqkHCy8gAhPpuUBs This is the **Weapon **script.

https://paste.ofcode.org/WEfdtb4FBRGidcS82khkDp this is the UIManager script.

https://paste.ofcode.org/JpVE3fPRxfPGML2Xdg6V9K This is the PlayerManager script.

https://paste.ofcode.org/jjUDwVnSMaHNUFtKAJVWEm This is the **GameManager **script it may be related.

https://paste.ofcode.org/34i8Zjfv7evzxnndgXcnkky This is WeaponSwitcher script it may be related.

https://paste.ofcode.org/33XETzHvy5ckxUCTrS4nVHF This is the UIVirtualJoystick script is on the Unity Starter Assets Fps Controller, and is a child of the UI_Canvas_StarterAssetInputs_Joysticks
UIVirtualJoystick is designed to handle touch controls for a virtual joystick UI element in Unity.
It allows the player to control movement or other actions by dragging a handle within a defined range.

https://paste.ofcode.org/HCPSmbgfWPBn5iY72uwsc9 This is the FirstPersonController this script is on the Unity Starter Assets Fps Controller.
This FirstPersonController script that handles player movement and camera rotation in a first-person perspective. However, it doesn't include functionality for mobile touch controls, such as virtual joysticks.

random patrol
#

Ah yeah introduced in Unity 2017

native seal
#

is something like this possible? how can I combine two interfaces into one?

random patrol
native seal
#

how come? so is what I wrote correct?

teal viper
eternal needle
#

you dont really need that IHoverable as an interface

native seal
#

what should I use then?

random patrol
#

What you wrote is good yes. The generic situation is because it can’t make sure you aren’t using the same type twice(causing a conflict), but it is Solved by making a sub interfaces aka IMyBool : IMyInterface<bool> and IMyFloat : IMyInterface<float>

teal viper
#

Where did the generics come from?😅

eternal needle
random patrol
#

Just generally how interface works

native seal
#

i know but if I raycast to check for a component, i wont be able to call the other

#

so in my mind I should combine them no?

teal viper
open apex
#

accidentally deleted a script from assets

#

any way to get it back?

#

I clicked cancel on the last second

#

fuck my life

limber willow
#

is it in the recycling bin?

timber tide
north kiln
# open apex any way to get it back?

Other than the recycling bin, you should be using version control; it should not be as easy as accidentally deleting something to lose your project or assets

limber willow
vale karma
gaunt ice
#
public int x;
public int X{get{return x;}set{x=value;}}
```no idea why you need property here
vale karma
#

i practiced a bit with what getters and setters are used for, and plan to use some more code in those

summer stump
vale karma
#

auto-propertied?

summer stump
#

Typo

#

Properties

vale karma
#

lol what are thooooose

summer stump
#

public Vector2 Sensitivity { get; private set; }

#

No need for the lowercase sensitivity

vale karma
#

wait so does it create a variable Vector2 sensitivity or what?

summer stump
gaunt ice
#

it will create a backup field

vale karma
#

okay, so using Sensitivity is basically using sensitivity in its place?

gaunt ice
#

you dont need to care its name

vale karma
#

okay, i keep thinking of it as a function

gaunt ice
#

property is function

teal viper
vale karma
#

like you would use Sensitivity in your code and not sensitivity?

teal viper
#

Yes

vale karma
#

but technically it is still a variable its saving to

teal viper
#

If it has a setter, yes. That doesn't change the nature of reference vs value types though.

vale karma
#

im understanding it a bit more today than yesterday, makin some sense

teal viper
#

It's the same issue as yesterday: you can't modify a field of value type variable returned by a property.

vale karma
#

i recognize that, but i dont know how i would fix that

#

im looking at the error on the web atm

teal viper
#

I think I explained that yesterday too.

#

How do you modify transform.position?

#

Did you ever try setting transform.positon.x = someValue?

vale karma
#

yea i guess

teal viper
#

So you address it the same way.

brazen narwhal
#

it finds the gameobject correctly, however, it returns the localPosition when using position and not the world space position. any reason why?

tepid summit
#

is the script on pistol or barrel

teal viper
brazen narwhal
tepid summit
#

"world space position"

tepid summit
#

oof

brazen narwhal
#

thats why its weird

teal viper
tepid summit
#

whoops

tepid summit
#

you have been darkevicted!

brazen narwhal
teal viper
brazen narwhal
#

gotcha

#

stupid mistake

#

thanks

tepid summit
#

meh

#

we all make them

acoustic sun
#

I keep getting this error from Unity when I try to run the game

#

error CS2012: Cannot open 'D:\Unity Projects\game\Library\Bee\artifacts\1300b0aE.dag\UnityEngine.UI.dll' for writing -- 'The requested operation cannot be performed on a file with a user-mapped section open. : 'D:\Unity Projects\game\Library\Bee\artifacts\1300b0aE.dag\UnityEngine.UI.dll''

rich adder
acoustic sun
#

I did

rich adder
acoustic sun
#

I do not have a desktop unfortunately

vale karma
rich adder
wintry quarry
wintry quarry
#

The other class is irrelevant

vale karma
#

yea, but what am i doin that im not seeing

wintry quarry
#

You never assigned that reference

#

In fact you made it readonly, ensuring it can never be assigned

acoustic sun
#

Ohhhh so like a new folder to place it?

vale karma
#

LOL visual studio suggested i do that, of course its wrong ahha

wintry quarry
#

private readonly NewInputSystemValues InputValues

#

This is an unassigned reference

vale karma
#

okay, so i should assign it in start? and remoe the read only?

#

how do i keep its protection level though?

wintry quarry
#

Usually in Awake

rich adder
vale karma
#

oh crap i totally forgot about awake vs start and all that

acoustic sun
#

Sorry I got confused

vale karma
# wintry quarry Usually in Awake

i removed private readonly and put public just to test, and put it in the awake method, i got like one less error, but still the same

acoustic sun
#

But i am not sure how to do that if I have all of my projects saved

acoustic sun
#

Like I have a folder but its saying that the error CS2012 and how it cant be performed, something like that. I looked for soultions online such as restarting Unity and my laptop but it does not seem to help

rich adder
acoustic sun
#

How do I save it into another folder other than the one it is saved in? Because when I tried doing that, it would not let me

rich adder
wintry quarry
#

That's the main thing you need to do that you didn't do.

#

Wdym by "put it in the awake method"? Put what there?

vale karma
#

yea when that didnt work i put PlayerInputValues = new Vector2(0f, 0f);

#

and it still said the same thing

wintry quarry
#

What what didn't work

#

Show what you tried

vale karma
wintry quarry
#

That's the console window

#

Show the code that you tried

vale karma
#
{
    PlayerInputValues = new Vector2(0f, 0f);
}
wintry quarry
#

You haven't even made an attempt to do so

#

It's not going to work until you do

vale karma
#

i changed it to this public NewInputSystemValues InputValues;

wintry quarry
#

Ok and then... Did you assign it somewhere?

vale karma
#

ooohkay i see what ur sayin

acoustic sun
hybrid tapir
#

how do i check if a value was changed in the last frame?

   if (intVal != intVal) {
   
   }
}```
wintry quarry
vale karma
wintry quarry
#

The thing it is referencing is the copy of the script

vale karma
#

yes

wintry quarry
#

Do you understand what a reference is?

#

Think of it like a piece of paper that you can write an address on.

#

The variable is the piece of paper

#

The thing it's referencing is the actual house

#

But your piece of paper was blank. You didn't write an address on it

vale karma
#

that makes sense

#

i got that error solved, but one last error "Rotation quaternions must be unit length". I tried to normalize the line of code but didnt work

wintry quarry
#

What line of code

vale karma
#

58

wintry quarry
#

Which is...?

vale karma
#

rb.MoveRotation(BodyRotation);

wintry quarry
#

It's because that's getting called before you assign BodyRotation to anything

#

It's a default Quaternion, which is all zeros

#

Which isn't a valid Quaternion

vale karma
#

fixed gets called before update?

rich adder
wintry quarry
#

Yes FixedUpdate is before Update

vale karma
#

okay

acoustic sun
rich adder
wintry quarry
acoustic sun
rich adder
acoustic sun
#

Not at all

rich adder
#

ok well i don't have context and id rather not play 20 questions maybe give more info ?

acoustic sun
#

Ohh okay thank you so much then

#

So sorry

vale karma
wintry quarry
#

I don't know what you mean by that

vale karma
#

like i put BodyRotation = Quaternion.Euler(bodyRotationYOnly); which made the error go away, but i figured if you needed to use bodyRotationYOnly as well then ud need to call whatever gets that variable too

#

also no error codes but my character still cant look around loll probably bc i havent even attatched the camera to it

wintry quarry
#

Which is probably a zero vector

vale karma
#

i dont know what the right way to go about this is anymore

wintry quarry
#

I don't really know what you're trying to do here, but your code is definitely overcomplicated

vale karma
#

haha yes it is

wintry quarry
#

Like why do you have a Vector3 that only stores data in the y component