#💻┃code-beginner

1 messages · Page 531 of 1

languid spire
#

it's your code, you tell me

hushed rain
#

this code may or may not have been copy pasted from somewhere on youtube, but i do understand the first part of this i just dont know why there is a second stop wall run

sick jay
#

How do i get a raycast to ignore triggers? I dropped an object inside a trigger hitbox and couldnt pick it up anymore due to the raycast hitting the trigger instead of the object

hushed rain
#

after consulting with chat gpt I know what the second stop wall run does

ivory bobcat
#

Other than knowing what the functions do, you may sometimes want to see which function is being selected - log inside the conditional statements.

languid spire
hushed rain
#

because then i wouldnt be 100% sure if i were right

ivory bobcat
#

But GPT can be wrong UnityChanThink

hushed rain
#

i was about to say that

languid spire
#

and using GPT will definitely not give you that

ivory bobcat
#

Thus why it's avoided unless you know what you're doing but are simply leaving the heavy lifting to it or want to see what kind of monstrosity it would create.

hushed rain
#

true now that i think about it gpt could also be wrong

#

it still doesnt fix the issue that i couldnt trust that my assumptions on what it does are right

ivory bobcat
#

But it's very convincing and thus would have you playing mind games with yourself in the debugging of critical errors.

languid spire
#

Looking at your code, if that came from a random yt tutorial, it is absolute rubbish

languid spire
#

oh, what a surprise, more click bait

hushed rain
#

i mean i wouldnt say that

languid spire
#

but you don't know enough to evaluate it, I do

hushed rain
#

fair enough

#

oh and btw regarding the question i asked you earlier about the dollar sign and you saying its neater, i agree but i learnt that from brackeys who alot of people think is very reliable

languid spire
#

brackey is crap

#

I noticed in your Lerps, you are using Brackey Lerps which are just plain wrong

hushed rain
#

what do you mean plain wrong, like they dont work at all?

languid spire
#

no, they kinda work.
Lerp is current = start, end, t where t moves from 0 to 1
you are doing
current = current, end, constant

ivory bobcat
hushed rain
#

oh ok

languid spire
#

what I hate most about Brackeys is that, even after having his code shortcomings pointed out to him over many years he could not be arsed to go and correct them

magic panther
#

I'm trying to read a config .xml file into a list of objects for later use (Translating the list into a bunch of tuned objects), but when I run this script I get a pretty hefty "FormatException: Input string was not in a correct format". If someone has a bit of time to spare, please ping me, any help here is appreciated

BGHolder Class --> https://hastebin.com/share/bocubitalu.csharp
BGlayersConfig.xml --> https://hastebin.com/share/aculaderaj.xml
-# Extra Information
Defaults --> https://hastebin.com/share/perajagili.csharp ||(I know about the virtual issue)||
BGLayer Class --> https://hastebin.com/share/giyorimumi.csharp

-# I don't know the complexity of this, so it might not belong in this channel, tell me if that's the case

ivory bobcat
magic panther
#

you mean Debug.Log(config)?

ivory bobcat
magic panther
#

one second

#

here @ivory bobcat

ivory bobcat
#

So the error line would be

DefaultJrlGameObject.PathToXmlObject[T] (System.String relativeFilePath) (at Assets/Scripts/Defaults.cs:59)

#

Which would be the virtual function ```cs
virtual protected T PathToXmlObject<T>(string relativeFilePath) {
string fullPath = Path.Combine(Application.dataPath, relativeFilePath);

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (FileStream stream = new FileStream(fullPath, FileMode.Open)) {
        return (T)serializer.Deserialize(stream);
    }
}```where you weren't able to deserialize the stream.
#

Where it stated that

There is an error in XML document (33, 5)

magic panther
#

line 33?

ivory bobcat
#

Maybe check out your xml file and see if there really is something incorrect there or not.

magic panther
#

seems to me that the xml is proper, maybe the XMLBGLayersConfig is wrong, but that also seems fine to me

#

I sent them in the message, maybe you can see something odd

ivory bobcat
#

With only the first background layer within the xml script, are you still able to reproduce the error?

magic panther
#

I'll see

#

what the hell, there's no error

ivory bobcat
#

The main differences between the two that I see outright would be the second using negative values and the color field being 8 hexadecimal values instead of 6

#

Big brain moment hopefully

magic panther
#

something weird happens

#

when there's only the first one, there's no error, when there's only the second, there is, when I paste the same values to the second one there's also an error, and when there's only the second with the same hex color as the first one, there is an error

#

I'll write it down:
#1 alone - no error
#2 alone - error
#1 and #2 with #1 values - no error
#2 with #1 color - error

ivory bobcat
#

Not sure. Maybe the serialization doesn't accept more than one background layer. Try a duplicate layer for the second layer (I don't know much about serialization or rather what exactly you're trying to serialize)

magic panther
#

it's meant to work with alpha values in the color, negatives in the X,Y areas and multiple BGLayers

#

yeah the problem lies in the second one

ivory bobcat
#

Can't fit a square into a triangle (assuming both have the same radius, relative to shapes)

magic panther
#

It's the X being negative

#

the color is fine

#

Man this is weird

#

why can't it read the negative X but reads a negative Depth just fine

ivory bobcat
#

It would depend on the type you're trying to serialize it as - XMLBGLayersConfig

magic panther
#

that just has a list of BGLayers

ivory bobcat
#

So a unity Vector2 field.

#

Not sure why it wouldn't let. Maybe serialize a bg layer as xml and see how it handles negative values UnityChanThink

magic panther
#

I don't get it

#

wwait maybe it's a negative float causing issue

#

IT'S A FLOAT

#

maybe eureka

#

hold up there's no error

#

give me 2 minutes to test something

ivory bobcat
#

You've got all of the time in the world. There are plenty of folks here who're listening and may comment on an issue. Keep at it and good luck.

magic panther
#

thanks for the help mate

twilit rivet
#

hallo

#

do i have to rewrite the whole code again just for walking and running animation?

#

void Update()
{
verticalInput = (Input.GetAxis("Vertical"));
horizontalInput = (Input.GetAxis("Horizontal"));
jumpInput = (Input.GetAxis("Jump"));
transform.Rotate(Vector3.up * horizontalInput * speed * Time.deltaTime * turningSpeed);
transform.Translate(Vector3.forward * verticalInput * Time.deltaTime * speed);
transform.Translate(Vector3.up * jumpInput * Time.deltaTime * jumpheight);
}

shell matrix
#

hello, i have a problem and idk what can i do to resolve this. So, I can't put with drag and drop from idle to controller.

timber tide
#

Not a coding question nor is that a game object with a runtime animator controller

shell matrix
glass sand
#

so i put tilemap collider but it seems to not be working

#

anyone know a guide to do it in unity 6 or no?

ivory bobcat
glass sand
ivory bobcat
#

Unless the tile map moves, you can opt to remove the rigid body component from the tile map.

ivory bobcat
glass sand
#

i have put rigidbody2d on it

ivory bobcat
#

Can you show it's inspector?

glass sand
ivory bobcat
#

Does the white box have a collider?

glass sand
#

no

#

maybe that's the issue?

ivory bobcat
#

Well, try giving it one

glass sand
#

it worked

#

thx

spiral abyss
#

hi i recantly learned how to change the position of the collider along an animation but it takes a while moving it in each frame is there any way to do it faster?

rancid tinsel
#

how do you do this? im still a bit sleepy i feel im missing the obvious

#

essentially having a factory create a GameObject with a script on it, then trying to assign that script to this.gameObject

slender sinew
#

I think you have some kind of misunderstanding, you can't have the same instance of a component on multiple GameObjects

languid spire
#

you would need to instantiate a new Settler on this gameobject and then clone thisSettler into it

hollow zenith
#

Does coroutine yield return new WaitUntil(() => variable); return at this point or does it continue after the line?
Is there a way to stop coroutine from going further like break?

short hazel
#

It'll continue after the condition is successful, you can use yield break; to exit the coroutine immediately, similar to using return; in a regular method

#

You cannot do that from inside the lambda expression though, as it's not a coroutine

hollow zenith
#

Makes sense, thanks

severe drum
#

hey ppl, im having some trouble with LOD that looks like my culling distance is restoring the full mode

#

anyone knows why?

#

here i disabled most of the renders in LOD

#

this is when it hits culling distance

short hazel
#

Else, show the code!

severe drum
#

sorry, untiy talk looked more like genral chat. i was nto sure about say it there

foggy crypt
#

I'm making multiple usable objects via OnTriggerEnter CompareTag.
I want those objects to be deactivated when you use them.
How do I refer to the exact object that I'm using, instead of deactivating them all via Tags?

languid spire
#

If you 'make' objects using Instantiate it returns the 'made' object

twilit rivet
#

😭 i got ignored

#

again

#

hallo
do i have to rewrite the whole code again just for walking and running animation?
void Update()
{
verticalInput = (Input.GetAxis("Vertical"));
horizontalInput = (Input.GetAxis("Horizontal"));
jumpInput = (Input.GetAxis("Jump"));
transform.Rotate(Vector3.up * horizontalInput * speed * Time.deltaTime * turningSpeed);
transform.Translate(Vector3.forward * verticalInput * Time.deltaTime * speed);
transform.Translate(Vector3.up * jumpInput * Time.deltaTime * jumpheight);
}

foggy crypt
languid spire
twilit rivet
#

:/

maiden swift
#

How to normalize scale of a sprite? I currently have [2.1111, 2.1111, 2.1144], how do I turn it into [1,1,1] while conserving the same size

twilit rivet
#

can anyone plz help me

wintry quarry
#

Not a code question though

foggy crypt
languid spire
#

then, surely, you already have a reference to them

twilit rivet
#

💀

#

lmao i got ignored again

rocky canyon
#

what is that u want? someone to help u rewrite ur code?

cosmic quail
rocky canyon
#

^ facts, use rigidbody functions.. or switch to a character controller and use Move()

copper kettle
#

is it possible to fix this? Thanks

languid spire
#

also !code

eternal falconBOT
copper kettle
#

Sorry, first time

languid spire
#

Also TerrainData is a Unity class, you really should not have your own with the same name

rancid tinsel
#

umm im getting this error until I open the object in the inspector, then the issue disappears for that instance

#

any clue at all what this could be

#

im working with a group mate's bit of code so its a lot harder for me to debug

#

my best bet is something to do with [System.Serializable] maybe

rich frost
#

Hey everyone, when I try to instantiate prefabs, they don't animate. They instead stay in their Idle animation, even when I mess with the blend tree manually.

Here's my code:


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

public class SpawnEnemies : MonoBehaviour
{

    public GameObject Enemy;
    public int XCoord;
    public int ZCoord;
    public int EnemyCount;

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

        StartCoroutine(EnemySpawn());
        
    }

    IEnumerator EnemySpawn()
    {

        while (EnemyCount < 10)
        {
            XCoord = Random.Range(10, 20);
            ZCoord = Random.Range(10, 20);
            Instantiate(Enemy, new Vector3(XCoord, 0, ZCoord), Quaternion.identity);
            yield return new WaitForSeconds(5);
            EnemyCount++;
        }
    }
 
}

Any thoughts on how to remedy this? Thanks!

languid spire
rich frost
polar acorn
cosmic quail
rancid tinsel
#

any idea why the issue is tied to opening something in the inspector at runtime?

languid spire
#

As it's a runtime error I fail to see how it can be generated by opening an inspector

rancid tinsel
#

its almost like it cant see the value until i open the object in the inspector

#

its really weird ill see if i can record it

#

whats also weird is some information like the name and some others work fine, it usually throws the error when it gets to health or attack

cosmic quail
cosmic quail
rancid tinsel
cosmic quail
#

or did you just post it here as a show off

rancid tinsel
#

chill out dude I've already tried to fix it and ran out of ideas which is why I'm asking for help

cosmic quail
rancid tinsel
#

I'd rather not show the script since it is a friend's work and I can't ask for permission right now

languid spire
#

then at least show line 51

rancid tinsel
#

it seems it has absolutely no issue until it gets to values.stats.attack which then throws a nullreference

languid spire
#

so values.stats is null

rancid tinsel
#

but then why would they suddenly not be null when opened in the inspector

languid spire
#

because they are being initialzed somewhere else

cosmic quail
languid spire
#

opening in the inspector has absolutely nothing to do with it

lapis veldt
#

hello. I have this issue with my jumping animation. It's working when the character is not moving, but when I move (ignore the character sliding left/right/back, I will work on it later) to any direction, it barely jumps

rancid tinsel
#

seems youre right

delicate vortex
#

I am still starting out and unsure thats why I am asking. If the bool is ture does the code run or does it just always run?

short hazel
#

Always runs

delicate vortex
#

Okay thanks

short hazel
#

This will print "true" or "false" in the console, depending on the value you passed to this method

rancid tinsel
delicate vortex
#

Sorry for needing help again. I got one program which declares and adds values to the int stars. In a different program I want to access the value of stars and I dont know how, does anyone have an idea on how I could achieve this?

languid spire
#

wdym by program

delicate vortex
#

2 different CS files

languid spire
#

so 2 different classes

delicate vortex
#

Yeah

languid spire
#

see the pinned messages here under General

delicate vortex
#

Thanks a lot!

#

The tutorial I followed about C# didnt go over this :c

sharp abyss
#

What can be reason they dont collide? I did debugs they were colliding but they dont effect each other.

#

also anybody have any idea for detecting damage? When I hold my sword to block enemys sword, because normally enemy runs to me , he collides with my sword and takes damage

sharp abyss
sterile radish
#

how do i save a dictionary with keys being strings and values being bools using a binary formatter?

rare basin
#

Never use binary formatter

#

It's obsolete and should not be used

#

It is unsecured and cannot be secured in any way

polar acorn
polar acorn
delicate vortex
polar acorn
#

Well if you've already decided you're too stupid to try then there's no point in continuing

delicate vortex
#

But here we go again I suppose. I got this class with the int Stars and I want to get the value of stars in a different class

polar acorn
formal escarp
#

im losing my mind

delicate vortex
sterile radish
#

how to save/load dictionaries using json serialization?

formal escarp
#

I have 2 gameobjects. Both of them have 2D Colliders. One of them has a "IsTrigger" on them, the other one (the one supposed to be destroyed) has the correct tag but nothing happens. i feel like im having tunnel vision

polar acorn
cosmic quail
delicate vortex
polar acorn
delicate vortex
#

Well the only way I have learned it so far is putting static in front of the class to then refer to it but I was told not to do that

cosmic quail
polar acorn
#

You should look at the thing I linked

delicate vortex
delicate vortex
#

or without public

formal escarp
cosmic quail
polar acorn
formal escarp
polar acorn
formal escarp
#

It should still work. It worked B4 with player and enemies system.

#

I feel like im missing something extremely simple.

polar acorn
formal escarp
#

Object i wanna destroy. Object which should be the destroyer.

polar acorn
#

Static rigidbodies do not move, and therefore do not collide

#

Other rigidbodies can collide with them

#

But a rigid body needs to be moving, as per commandment 3

formal escarp
#

If its not static it would fall to the void. ill make a quick base floor quick but it still wont work

#

im losing all faith. all hail 3D

polar acorn
#

You need to just not half ass it and actually implement a rigid body

formal escarp
#

It worked 💀

formal escarp
polar acorn
#

Rigidbody calls all of its collision functions when it moves into a collider

#

If a rigidbody is not moving, the functions don't get called

formal escarp
#

It always needs to be Dynamic then?

#

In these types of cases*

polar acorn
#

static rigidbodies do not move

formal escarp
#

I know but.

polar acorn
#

So, therefore, a static rigidbody cannot move into a collider

formal escarp
#

Yeah nvm. Now i see why my question was dumb 💀 thanks again g.

#

I should have used gravity 0 instead of changing it to Static.

sterile radish
#

how can i make this json save system save dictionaries? it saves other data types perfectly fine but for some reason the dictionary i want to save doesnt get saved through this system and resets back to its default values
https://hatebin.com/nmbhbnefeo

polar acorn
half jolt
#

What's the proper way to do mobs? I know it depends, but still. The tutorials I'm seeing seem either too simple or too complex. I'm trying to make something dynamic, since I'm making animals, like bunnies, deer and dogs, but I'd like to make bosses too while reusing as much code as possible. Is it really necessary to make a script for each creature?

sterile radish
polar acorn
sterile radish
#

!code

eternal falconBOT
sterile radish
slender nymph
#

line 11 cannot throw a NRE, however the variable on line 11 is null because you don't assign it anywhere

#

what you could do instead of that foreach is just do FlagNames = GameManager.Instance.flags.Keys.ToList(); and do the same for the FlagValues and the Values

sterile radish
# slender nymph line 11 cannot throw a NRE, however the variable on line 11 *is* null because yo...

yes it seems so but im not sure how? i probably shouldve mentioned this but i have a script for the player which has its own method that retrieves saved data. i made a for loop that sets the flag values to the saved flag values so how is it still null? (below is the for loop im talking abt for reference)

        for (int i = 1; i < GameManager.Instance.flags.Count; i++)
        {
            GameManager.Instance.flags[data.FlagNames[i]] = data.FlagValues[i];
        }
slender nymph
#

the variable on line 11 is null because you don't assign it anywhere

sterile radish
#

i thought i was assigning it in this line, no? FlagValues = GameManager.Instance.flags.Values.ToList();

#

actually hold on

slender nymph
sterile radish
slender nymph
#

that does not create an instance of the list. which is why it is still null. that is the line that is actually throwing the NRE

sterile radish
#

ohh okay

slender nymph
#

again, you have to actually assign to the variable somewhere or else it will be null

sterile radish
#

actually sorry im a bit confused. my line didnt create an instance of the list. so i have reqritten my code to this.


        FlagNames = new List<string>();
        FlagValues = new List<bool>();

        foreach (KeyValuePair<string, bool> pair in GameManager.Instance.flags)
        {
            FlagNames.Add(pair.Key);
            FlagValues.Add(pair.Value);
        }

now for actually assigning the FlagValues variable, im confused on where exactly im supposed to be assigning it?

slender nymph
#

those lines that you just added are assigning

#

or you could erase all of that and use what i suggested

sterile radish
#

by "erase all of that" are you referring to the foreach loop or the entire code block i pasted rn?

slender nymph
#

google what the definition of "all" is

delicate vortex
#

Why does one work and the other doesn't?

eternal falconBOT
sterile radish
slender nymph
#

now show how you have determined that as well as where you call the LoadPlayer method

delicate vortex
slender nymph
#

show where you actually assigned to the variables

delicate vortex
#

but one works

slender nymph
#

you have assigned one of those variables somewhere. probably in the inspector, but that is just a guess

polar acorn
#

With your eyes, Bert

delicate vortex
slender nymph
#

prove it. show the entire class and where you've assigned it

delicate vortex
slender nymph
#

reading is hard, huh?

polar acorn
delicate vortex
#

But why does one work then?

slender nymph
polar acorn
cloud gust
#

Does anyone know how i fix that Visual Studio is detecting the Unity functions as unreachable code and fades them out?

delicate vortex
#

Well this is all the code I have, I just have some objects and thats it

polar acorn
eternal falconBOT
delicate vortex
#

I appreciate you help and patience

delicate vortex
#

I did check but I checked in the TMP_Text "income" and "counter" but not in the canvas, because I didnt know where they even get assigned

#

I followed a tutorial for the first one

cloud gust
# slender nymph !IDE 👇

i did that, visual studio is also having the functions tagged with "unity message" but still is fading them out

slender nymph
# delicate vortex I followed a tutorial for the first one

at this point you need to stop whatever it is you are doing and actually go learn the basics. if you don't know the basics of c#, then start with the beginner courses pinned in this channel. then afer you learn that, do the essentials and programmer pathways on the unity !learn site

eternal falconBOT
#

:teacher: Unity Learn ↗

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

pure drift
#

how can i fix out greyed out code in unity its happening in all of my projects and no matter what i try i cant fix it

delicate vortex
# slender nymph at this point you need to stop whatever it is you are doing and actually go lear...

I watched this tutorial about C# https://www.youtube.com/watch?v=wxznTygnRfQ

C# tutorial beginners full course (C# for Unity)
#C# #tutorial #Unity
⭐️Time Stamps⭐️
#1 (00:00:00) C# tutorial for beginners 🚀
#2 (00:06:30) output 💬
#3 (00:10:48) variables ✖️
#4 (00:19:32) constants π
#5 (00:20:35) type casting 💱
#6 (00:27:49) user input ⌨️
#7 (00:31:24) arithmetic operators 🧮
#8 (00:35:54) Math class 📏
#9 (...

▶ Play video
#

but never watched one about Unity

#

which I should do

slender nymph
delicate vortex
#

Yes I will do that too I just didnt mention it

slender nymph
pure drift
#

im sure everything is upto date its just that i did something with intellisense that broke it

cloud gust
cloud gust
pure drift
#

yeah i cant find any fixes i might be cooked

upper forge
#

How would I get my enemy to jump over a gap/pit?

slender nymph
little raft
#

where i should ask for support on why my 3D model isn't placing corectly on a grid? (i m trying to make a building sistem fallowing up Sunny Valley Studio's tutorial)

little raft
#

idk what is my problem exactly, code or just 3D procesing 😦

slender nymph
#

then ask your question in whatever channel it is you think is most relevant to your issue and provide actual details

little raft
#

firstly this is what i imported as a .obj file:

#

TF I SOLVED THE PROBLEM JUST BY CHANGING THE Z OF THE 3D MODEL

#

ty anyways

slender nymph
#

by changing the z of the 3d model
or do you mean by changing the Z axis on the child object of the prefab so that it lined up exactly with the parent object which is what you were placing?

icy crag
#

Hey what program language does unity use? i forgot

slender nymph
#

you can also use google to find information

icy crag
#

ok thank you for the help 😀

icy crag
#

Hmmm? ok

icy crag
#

Can you tell me what the difference is because they came from the original C program

naive pawn
#

a ton of stuff came from C. doesn't mean that they're the same

wooden bobcat
#

They're two different languages. They have similarities, but ultimately they're different.

naive pawn
#

google should be able to tell you their differences

icy crag
#

Ok thank you because I'm learning from Codecademy

slender nymph
tranquil zealot
#

someone please help im stuck in a lot of spaghetti

slender nymph
#

!ask

eternal falconBOT
terse raven
#

help me pls its driving me nuts!

naive pawn
#

have you tried restarting the editor

terse raven
#

yep they keep coming back

tranquil zealot
#

okay so its a top down plane shooter game and im implementing an archetype system with passive skills and abilities and shit. its like a skill tree system where you can unlock more skills after unlocking the ones prior. im getting really burnt out just with the skill interface menu and shit.

So theres 4 classes that are responsible for my skill system

PlayerSkills (singleton) - holds all skills and handles their activation
TreeManager (singleton) - manages the trees activation
SkillTreeManager - handles the SkillTreeScene and some UI in it
SkillNode - script given to each skill in a tree (UI button)

How it works is in a panel, theres 2 skill trees that cant both be activated at the same time, so if one is activated all the other skills in the other tree should be deactivated.

The skill nodes that are activated, but then deactivated due to activating another tree are remembered and reactivated when their tree is reactivated.

The issue -

When i start the game and go into SkillTreeScene, both the trees are deactivated on start. then when i click on one of the trees, and unlock some skills in it, then go back to another scene, then go back to SkillTreeScene, it remembers them just fine. but when i select one tree, then select another tree (deactivating the first one and all its skills) and exit the scene (SkillTreeScene) and reenter it, it forgets every single skill that was active, even though these skills are being stored in the singleton PlayerSkills.

DM me and i could show you pictures and videos of the error

sand snow
#

for some reason when i jump my character kinda teleports upwards and also he falls super slow to the ground

here is the script

public class PlayerMovement : MonoBehaviour
{
    public float speed;
    public float jumpForce;
    [SerializeField] private Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate()
    {
        rb.velocity = new Vector3(Input.GetAxisRaw("Horizontal") * speed, 0, Input.GetAxisRaw("Vertical") * speed);
        
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(0, jumpForce, 0, ForceMode.Impulse);
        }
    }
}```
naive pawn
#

you're setting the y velocity to 0 in fixedUpdate

#

you'll want to avoid that and let gravity control the y velocity

sand snow
#

so how do i do that

naive pawn
#

you could just set it to itself, ie replacing 0 with rb.velocity.y

sand snow
#

oh okay

#

i was trying to figure that out

naive pawn
#

or you could extract out the velocity first, and then set only the x and z values, leaving y untouched

sand snow
#

i thought it was something like current.position or something

#

and i couldnt remember what it actualy was

#

thank you so much

naive pawn
#
Vector3 vel = rb.velocity;
vel.x = ...
vel.z = ...
rb.velocity = vel;
tranquil zealot
teal viper
upper yoke
#

Hey, I have a game with audio mixers, where I use SetFloat in Start() to set their initial volume
It works for my background music that is played in the menu, but not for sounds that are only played in the main scene
I found this topic that sounds similar to my problem: https://discussions.unity.com/t/audiomixer-volume-setfloat-on-exposed-parameter-doesnt-work-when-mixer-inactive/813786
And this point sound relevant: After you play a sound on the mixer it gets active and you must then initialize the values?
If it's the issue, is there a way to "force" an audio mixer to be active?

open vine
#

Hey, does anyone know how to I would make a 3D dash using a character controller for the player on a button press? I got the input registered to a dash method, but I don't know how to make the charactercontroller move a certain distance over a duration, I only got it to move the distance in an instant.

naive pawn
#

you could set it at a certain (higher-than-walking) velocity for some period of time

wintry quarry
open vine
#

Thank you I ended up changing the speed which worked

tiny hawk
#

Can I download a GIt repo through the Asset Manager window if the Git repo doesn't have a Manifest file?

#

While still being able to update the package through the package manager?

wintry quarry
tiny hawk
north kiln
#

Those methods are called by Unity, and have signatures that are incompatible with UnityEvent

supple wasp
#

People, the code has already been fixed, but there is another problem: the button is not activated.

#

!code

eternal falconBOT
supple wasp
polar acorn
supple wasp
#

This button is already active but when the player gets on the button is deactivated instead of activated.

polar acorn
#

It appears to deactivate the button in Start, and activate them whenever you call ActivarBotonSalir

supple dune
#
using UnityEngine;

public class DiceThrower : MonoBehaviour
{
    public GameObject dicePrefab; // サイコロのプレハブ
    public Transform spawnPoint; // サイコロの生成位置
    public float throwForce = 0.1f; // 投射する力
    public float throwAngle = 45f; // 投射角度

    private GameObject dice; // 投射されたサイコロ
    private Rigidbody diceRb;

    void Start()
    {
        // サイコロを生成
        SpawnDice();

        // 5秒後に力を加える
        Invoke(nameof(ApplyForceToDice), 5f);
    }

    void SpawnDice()
    {
        if (dicePrefab == null || spawnPoint == null)
        {
            Debug.LogError("Dice Prefab または Spawn Point が設定されていません!");
            return;
        }

        // サイコロを生成
        dice = Instantiate(dicePrefab, spawnPoint.position, Quaternion.identity);

        // Rigidbodyを取得または追加
        diceRb = dice.GetComponent<Rigidbody>();
        if (diceRb == null)
        {
            diceRb = dice.AddComponent<Rigidbody>();
        }

        diceRb.useGravity = true; // 重力を有効化
        diceRb.isKinematic = false; // 物理演算を有効化
    }

    void ApplyForceToDice()
    {
        if (diceRb == null)
        {
            Debug.LogError("Rigidbodyが見つかりません!");
            return;
        }

        // 投射方向を計算
        Vector3 throwDirection = CalculateThrowDirection();

        // 力を加える
        diceRb.AddForce(throwDirection * throwForce, ForceMode.Impulse);
        Debug.Log("AddForce applied. Direction: " + throwDirection + ", Force: " + throwForce);
    }

    private Vector3 CalculateThrowDirection()
    {
        float angleRad = throwAngle * Mathf.Deg2Rad; // 角度をラジアンに変換
        float x = Mathf.Cos(angleRad); // X成分
        float y = Mathf.Sin(angleRad); // Y成分

        return new Vector3(x, y, 0).normalized; // X方向に投射
    }
}
#

I want to create a script that throws dice.

I succeeded in generating dice in advance and flying them.
However, when I tried to generate dice and cast them in the script, a problem occurred.

For some reason, a huge force is applied to the dice and they fly off into the distance.
I adjusted the air resistance numbers, but it made the problem worse.

For reference, if you create the dice in advance and throw them, the projected power is 4.

eternal falconBOT
supple dune
#

Is this okay?

frosty hound
#

You didn't post anything

supple dune
#

Can you see it?

using UnityEngine;

public class DiceThrower : MonoBehaviour
{
    public GameObject dicePrefab; // サイコロのプレハブ
    public Transform spawnPoint; // サイコロの生成位置
    public float throwForce = 0.1f; // 投射する力
    public float throwAngle = 45f; // 投射角度

    private GameObject dice; // 投射されたサイコロ
    private Rigidbody diceRb;

    void Start()
    {
        // サイコロを生成
        SpawnDice();

        // 5秒後に力を加える
        Invoke(nameof(ApplyForceToDice), 5f);
    }

    void SpawnDice()
    {
        if (dicePrefab == null || spawnPoint == null)
        {
            Debug.LogError("Dice Prefab または Spawn Point が設定されていません!");
            return;
        }

        // サイコロを生成
        dice = Instantiate(dicePrefab, spawnPoint.position, Quaternion.identity);

        // Rigidbodyを取得または追加
        diceRb = dice.GetComponent<Rigidbody>();
        if (diceRb == null)
        {
            diceRb = dice.AddComponent<Rigidbody>();
        }

        diceRb.useGravity = true; // 重力を有効化
        diceRb.isKinematic = false; // 物理演算を有効化
    }

    void ApplyForceToDice()
    {
        if (diceRb == null)
        {
            Debug.LogError("Rigidbodyが見つかりません!");
            return;
        }

        // 投射方向を計算
        Vector3 throwDirection = CalculateThrowDirection();

        // 力を加える
        diceRb.AddForce(throwDirection * throwForce, ForceMode.Impulse);
        Debug.Log("AddForce applied. Direction: " + throwDirection + ", Force: " + throwForce);
    }

    private Vector3 CalculateThrowDirection()
    {
        float angleRad = throwAngle * Mathf.Deg2Rad; // 角度をラジアンに変換
        float x = Mathf.Cos(angleRad); // X成分
        float y = Mathf.Sin(angleRad); // Y成分

        return new Vector3(x, y, 0).normalized; // X方向に投射
    }
}
#

I want to create a script that throws dice.

I succeeded in generating dice in advance and flying them.
However, when I tried to generate dice and cast them in the script, a problem occurred.

For some reason, a huge force is applied to the dice and they fly off into the distance.
I adjusted the air resistance numbers, but it made the problem worse.

For reference, if you create the dice in advance and throw them, the projected power is 4.

teal viper
supple dune
supple dune
teal viper
tranquil zealot
supple dune
teal viper
teal viper
# supple dune it is console

Try reducing the force. The dice is very small and lightweight, so force of 5 is probably enough to launch it into space.

supple dune
#

I tried changing it in the range of 0.1-0.01, but it stayed the same and flew into space!

If I drag & drop the prefab directly into the Hierarchy without scripting the dice, I can throw it with a force of 4 just fine.

supple dune
#

If you generate dice with a script, it won't work.
I wonder why

teal viper
supple dune
#

OK
I will Try

teal viper
#

Also, maybe don't do Invoke see if the issue occurs if you call it from fixed update once.

supple dune
#

But may be same one
Because copy both...(´;ω;`)…

supple dune
acoustic belfry
#

Hi, i tried to make an enemy wander, but something went wrong, it just...stands in there...frozen... why?

this is the code:


public class tuetue_script : MonoBehaviour
{

    public int rutina;
    public int cronometro;
    public Animator ani;
    public int direccion;
    public float speed_walk;
    public float speed_run;
    public GameObject target;

    void Start()
    {
        ani = GetComponent<Animator>();
        target = GameObject.Find("Valeria");


    }

    public void Comportamientos()
    {
        ani.SetBool("tuetue_run", false);
        cronometro += (int)(1 * Time.deltaTime);
        if (cronometro >= 4)
        {
            rutina = Random.Range(0, 2);
            cronometro = 0;
        }

        switch (rutina)
        {
            case 0:
                ani.SetBool("tuetue_walk", false);
                break;

            case 1:
                direccion = Random.Range(0, 2);
                rutina++;
                break;

            case 2:

                switch (direccion)
                {
                    case 0:
                        transform.rotation = Quaternion.Euler(0, 0, 0);
                        transform.Translate(Vector2.right * speed_walk * Time.deltaTime);
                        break;
                }
                ani.SetBool("tuetue_walk", true);
                break;
        }


        // Update is called once per frame
        void Update()
        {
            Comportamientos();
        }
    }
}```
teal viper
acoustic belfry
teal viper
languid spire
solemn fractal
#

Hey guys not sure but that seems to be related to the code of the buttons UI that I didnt do anything and suddenly appeared.. any ides?

#

never touched that in my life..

#

out of a sudden this happened and even if I close and open wont fix.

teal viper
solemn fractal
#

Reset .. closed all .. opened again

#

still the same 😦

#

hope I didnt lose my 3 months work haha

teal viper
solemn fractal
#

no.. if I open the unity the error is already there. That happened first time when I hit play in the game, and clicked in one of the button.

#

but now just opening the unity the error is already there

teal viper
#

Very weird.

solemn fractal
#

if I click in any button now I cant select the button action it wont open the dropdown

#

if I click here nothing happens

teal viper
#

What components does the UserInterface object have?

#

Does it happen if you replace it with any other object?

solemn fractal
#

hmm it fixes the prob if I dont use the UserInterface.. ok i will check further..

teal viper
#

Does it have any components with broken references perhaps?

solemn fractal
#

it seems like one of my components for some reason is like that now:

#

Will remove it now and might fix but have no idea how that happen.

#

that fixed the prob.. thank you

acoustic belfry
#

the actor doesnt have gravity, i mean, doesnt fall, and its static, like when i just made it

#

Like if were just a plain draw on the plane

languid spire
fleet onyx
#

Hello! Does someone know what is going on here? Of course, I have installed correctly the TextMesh Pro package correctly and since yesterday it didn't give any problem. Also, when I run the game in editor, the console doesn't show any errors and the game runs just fine.

acoustic belfry
#

but...are u sure thats all? Im gonna check later cuz im not currently at my pc and is early

languid spire
acoustic belfry
#

i mean

#

delete the 0

languid spire
#

do you never read documentation?

acoustic belfry
#

I mean, i dont even know of the existence of the objects, i just follow tutorials and analyze for myself how it works

#

sorry...

languid spire
#

go and read the Random.Range documentation
in fact, when you know so little, 90% of your time should be spent reading the docs

frail hawk
languid spire
fleet onyx
#

thanks, I will try

frail hawk
#

regenerate project files means what

fleet onyx
#

in preferences > external tools, you can choose to regenerate .csproj files

#

but I'm trying bot to restart editor and then regenerate those files

frail hawk
#

oh okay thought regenerate the library folder

languid spire
frail hawk
#

allright

fleet onyx
#

it still gives me error..

#

also, I tried what VS suggests, but it just suggests to delete them

languid spire
#

is the using still underlined?

fleet onyx
#

yes

languid spire
#

post the assembly-csharp.csproj file to a paste site

fleet onyx
#

it is really weird, just yesterday I made a build of the game and it didn't give any errors

#

today I open Unity and this happens

#

I'm thinking, maybe I could try deleting library folder and open again the project

frail hawk
#

you could try it in a fresh project and see if it is also giving the same error

fleet onyx
#

ok I tried deleting: Assembly-CSharp.csproj file, Library folder, .vs folder, .vs config file, questiquest.sln file (game name). Then restarted Unity Hub and opened Editor. Problem solved.

#

If any of you ever faces this issue, this worked for me

frail hawk
#

nice

fleet onyx
#

anyway thanks you all for trying to help, I appreciate a lot

languid spire
fleet onyx
#

yeah!

#

but when opening editor and making a build again, it seems regenerates again those files so it's ok i guess

proven matrix
#

Guys why are my start and update functions greyed out

languid spire
proven matrix
#

what do i do? downgrade?

languid spire
proven matrix
languid spire
#

no

#

this is a purely visual bug

north kiln
proven matrix
north kiln
#

Then you haven't gone through the all of the links, it's exhaustive as far as I know. If there's an unlisted fix for the issue then I'd love to know

wicked locust
#

hi , i want check the if light map Bake Type is real time or not , but when i want build the project , it give an error (SOLVED)

`Light[] Spot_Lights = FindObjectsByType<Light>(FindObjectsSortMode.None);
foreach (Light Spot_Light in Spot_Lights)
{
if (Spot_Light != null && Spot_Light.type == UnityEngine.LightType.Spot && Spot_Light.lightmapBakeType == LightmapBakeType.Realtime)
{
Spot_Light.shadows = LightShadows.Soft;
}

}

foreach (Light Spot_Light in Spot_Lights)
{
if (Spot_Light != null && Spot_Light.type == UnityEngine.LightType.Directional && Spot_Light.lightmapBakeType == LightmapBakeType.Realtime)
{
Spot_Light.shadows = LightShadows.Soft;

  }

}
`

slender sinew
wicked locust
hazy blaze
#

how do I call a function from another script ? I've been searching around for hours and either I cannot understand what is being said or i can't get it to work

languid spire
wintry quarry
burnt vapor
rocky canyon
astral citrus
#

Hi! Could you please help me to implement custom factory with Zenject?

I've done "basic" one that resolves context from GameObjectContext and returns facade to me from GameObject context to SceneContext. But I can't implement customization. The idea - I have enemy game context, that have livespan only when game object alive, and I create it via Zenject and provide EnemyEntity as facade for SceneContext(my manager class) to work with it, while other classes/objects of GameContext are hidden.

This code that works for me:

container
  .BindFactory<EnemyEntity, EnemyEntity.Factory>()
  .FromSubContainerResolve()
  .ByNewContextPrefab(enemyPrefab)
  .UnderTransform(worldTransform);

public class Factory : PlaceholderFactory<EnemyEntity> {}

But I want create my enemy using instantiate and pass position righ away to it, like I can do using container

container.InstantiatePrefab(enemyPrefab, position, Quaternion.identity, worldTransform)

Unfortunately I can't make it work, while implementing interface, FromSubContainerResolve not working for me, and using ootb I can't get how can I add some data to my object. This is what I've tried.

public class CustomFactory : IFactory<EnemyEntity>
  {
   ///Injections

    public EnemyEntity Create()
    {
        return _container.InstantiatePrefabForComponent<EnemyEntity>(_enemyPrefab, _worldTransform);
    }
  }
urban prawn
#

I want to have four types of enemies (different in hp, attack points, color and prefab). I thought I would best use a Scriptable Object for this. But I don't understand how each instance of those can have their own hp and not change that of every else. Is the scriptable object just attached to a normal mono script?

Also I want to have pooling for those enemies. Would it be best to have one pool and assign a prefab each time I release it?

proven matrix
#

The playfab sdk isnt installing when i click isntall sdk.. I get thrown this error

rich adder
rich adder
#

don't modify the values on the SOs or all the instances that use that value have the changes. Think static fields

urban prawn
#

Okay, so I understand that correctly.

nimble mortar
#

Does anyone know if there are rules for .editorconfig to get c# to convert this:

contextMenuItems.Add("Lock", new Dictionary<ContextMenuUIEventType, Action> { { ContextMenuUIEventType.MOUSE_UP, LockItem } });

to this:

contextMenuItems.Add(
  "Lock", 
  new Dictionary<ContextMenuUIEventType, Action> { { ContextMenuUIEventType.MOUSE_UP, LockItem } }
);

when the line length is exceeded?

I can only get it to format like this automatically:

contextMenuItems.Add("Lock",
  new Dictionary<ContextMenuUIEventType, Action> { { ContextMenuUIEventType.MOUSE_UP, LockItem } });

Which for me is much harded to read as I always miss the first parameter since it is on the same like as the method call instead of its own line?

marble grotto
#

hi, i really need help with something. I'm not much of a coder. I'm trying to get a coin sound to increase in pitch per coin up to 5 then reset. (Also reset if theres a big enough gap per coin collected).

marble grotto
#

thanks, i'll read through it

solemn fractal
#

hey guys I just have no where in my code where it says that the currentArmor should be 0. And everytime I start the game, that value goes to 0. I am positive that there is no place in any script saying that. any ideas?

rich adder
#

[SerializeField] private those so you know for a fact its not being touched anywhere but within that script

#

make methods / property if you want to interact with it from elsewhere

solemn fractal
#

no they are not

#

That is my whole class, and I am not using yet any of these getters and setters.. also in the inspector before start the game they also have the value of 1

#

The only place they are set to zero is here, but I already used debug log and that only happen when the player is touched by an enemy, and it goes to 0 already at the start:

#

might be a visual bug

keen dew
#

Put a log in the setter, then you can check the stack trace where it was set

polar acorn
#

Chances are you're looking at the inspector of a different object than the one getting changed

magic panther
#

There's a very weird thing happening with my Image objects. I have a canvas, which creates some Image elements with a BGLayer component, and based on their Auto Scroll, scrolls them individually by that value (Via their own update method, independent of the parent canvas). I have just switched to canvas instead of sprite renderers to make this cleaner, and before that it worked fine. Layers with 0 auto scroll were still, while ones with anything but 0 (the clouds in this case), slowly moved by that amount every frame.
Now, as seen in the recording, all layers seem to move by the addition of all their individual autoscroll values (As in a 0;0, 0.5;0 and -0.2;0 are all moving at a speed of 0.3;0, the result of adding them all together (???). I have no idea why this might be happening. Can someone please help me figure this out?

-# Files:
Video #1 - Recorded problem
Screenshot #1 - BGLayer Prefab (all values (including the default sprite) are overriden when loading layers from the xml)
BGLayer Class - https://hastebin.com/share/hixecowuco.csharp
BGHolder Class - https://hastebin.com/share/toqoverigi.csharp
Tell me if any other files are needed

-# I repeat, this worked perfectly fine until I switched GameObject with SpriteRenderer to GameObject with Image

runic lance
#

althought I must say that using UI for this kind of stuff sounds unusual at least, sprite renderers are probably more adequate

magic panther
#

Creating a new material dynamically so far breaks it even more

runic lance
magic panther
#
    public void Assign() {
        imageRenderer = GetComponent<Image>();
        rectTransform = GetComponent<RectTransform>();

        Material unlitMaterial = new Material(Shader.Find("Unlit/Transparent"));
        imageRenderer.material = unlitMaterial;
    }
runic lance
#

I don't think that's the correct shader, you can probably just do:

Material mat = new Material(imageRenderer.material);
imageRenderer.material = mat;
magic panther
#

Sorry for not replying, wifi crash

#

Yeah I forgot canvas render above all

#

damn

untold shore
#

Hi! If Im doing anything of this in the wrong format tell me - I'm very new to this server, and would be happy to take this message down if needed.
So Im having an issue with my game elements not saving their position whenever I click a button (The "Draw Card" function under Deck Manager). Whenever I do, it will not save the previous positions of my objects, which I want them to save after a player moves them with their mouse. (Ex: player moves the card to the right, clicks draw card, that original card stays to the right while the other card is drawn).
Issue: Cards not saving position when function is called - want to get those positions to save so even if those functions are called, it stays that way

Codes:
CardMovement Script: https://paste.ofcode.org/vhBHVDSJDSY2afEXLVxDCM (This is what all card movements are linked up to, but it does not have the draw card function inside it.)
DeckManager Script:
https://paste.ofcode.org/6HcWvttWCQqnLgf9sB3qid (This is what actually calls for that Draw card function)
(If you do respond, please @ me! I usually miss responses very easily due to working on other problems. Thank you so much!)

potent tusk
#

how do i create a character that can move (ik this is simple but i just cant)

digital hawk
#

I tried to create a graph dialog system but I have problems. When I save and then load the graph, even if the nodes appear, the texts inside or the sprites and fonts no longer appear when loaded (before then after load)

runic lance
untold shore
digital hawk
runic lance
#

you'll need to add Debug.Log statements at every position change and figure out exactly where it's happening, then later it should be easy enough to prevent this change from happening in certain cards

runic lance
eternal falconBOT
potent tusk
#

i need help why do i only have the game scene

#

like i cant move my screen and i cant change scenes

#

this is the only thing i can see

frail hawk
#

reset your layout first it seems weird

#

also reset your scale

potent tusk
frail hawk
#

top right

#

add a camera to your scene

potent tusk
#

oh thank you

untold shore
# runic lance you'll need to add `Debug.Log` statements at every position change and figure ou...

Figured out where it was messing up, but I dont know how to generally fix it.

private void UpdateHandVisuals()
    {
        int cardCount = cardsInHand.Count;

        if (cardCount == 1){
            cardsInHand[0].transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
            cardsInHand[0].transform.localPosition = new Vector3(0f, 0f, 0f);
            return;
        }

        for (int i=0; i < cardCount; i++){
            float rotationAngle = (fanSpread * (i - (cardCount - 1)/2));
            cardsInHand[i].transform.localRotation = Quaternion.Euler(0f, 0f, rotationAngle);

            float horizontalOffset = (cardSpacing * (i - (cardCount - 1)/2));

            float normalizedPosition = (2f * i / (cardCount - 1));
            float verticalOffseat = verticalSpacing * (1 - normalizedPosition * normalizedPosition);

            //set card position
            cardsInHand[i].transform.localPosition = new Vector3(horizontalOffset, verticalOffseat, 0f);
        }
    }
}

The main thing that I need to do is get that card position to save even when drawing, but to do that it'll effect the new cards drawn position.

#

Apologizes for how messy that looks, need to figure out how to use the "``cs" command more

runic lance
#

huh that's weird

untold shore
#

There we go!

#

Pressed tab after cs, that's why it messed up 🤷

runic lance
untold shore
runic lance
#

most likely you'll also need to modify how you're counting the cards here
as far as I understood you'll want to keep the fanning effect for the cards that were not moved

sleek notch
#

Hi I have a question. I'm currently doing inventory by grid layout group. I have grid layout group and next grid layout group in it, if the second grid layout group has so much objects they will start overlap over next grid layout group. Does anyone know how to do better grid layout group?

#

Or is there better way how to do grid layout?

brittle isle
#

So I've been doing a 2d Mario-like platformer, and I'm trying to figure out a way to make the player, and all other characters and objects, move in parallel to slopes. I always slip off. Enemies walk away thinking it's a wall, too.

willow rune
#

When i type in update nothing comes up and so i cant get things done.

modest dust
#

What do you mean nothing comes up? It's literally there.

willow rune
#

no this image shows what im supposed to see

#

when i type it in nothing comes up

modest dust
#

Then send what you actually see instead

#

!ide

eternal falconBOT
willow rune
#

What to do now?

modest dust
#

Kindly read the bot message, click a link and follow the steps.

willow rune
#

how to move my visual studio community and its installs to another disk?

alpine fjord
#

The easiest way would be to uninstall it, restart your PC, then reinstall it in the location you want.

untold shore
#

Alright, been working on troubleshooting the counting card method from before.
Could someone explain to me what these errors mean? It's still giving me the Debug log after where it says the null failed, but it still says the Null failed. What happened?

short hazel
#

It comes directly after instantiating the object it seems

#

Something is null but you're trying to access it anyway

untold shore
#

Thats weird.
Heres the code there, but I dont get what its null?

        cardCount = GameObject.Find("DeckManager").GetComponent<DeckManager>().cardCount;
         Debug.Log("Found cardInHandCount");

If you wouldnt mind explaining that is. Thank you!

short hazel
#

This can error if no "DeckManager" object is found, or if it is but there's no DeckManager script on it

north kiln
short hazel
#

You can get NREs when you dereference (ie. access) with . on a null reference (a variable that is null or something that gives you null)

#

Like with a.b, if a is null, you get the error

polar acorn
#

So, GameObject.Find("DeckManager") or GameObject.Find("DeckManager").GetComponent<DeckManager>()

untold shore
#

Ohh! Yeah, it's probably because DeckManager becomes a clone, need to figure out how to exactly correct it

#

Thank yall for yalls help by the way! It's insanely useful!!!

lofty sequoia
#

hey I've got an image with a lot of alpha space in it and it's being picked up as the button press area. Is there a way I can have just inside the arrow be detected as button press?

#

I tinkered with alphaHitTestMinimumThreshold set to .5f on the image and set read/write on and it made the whole button invisible

teal viper
lofty sequoia
#

odd, I wonder why it's doing this. I'm doing an alpha fade on the object after it's instantiated, that's on the image sprite color

teal viper
lofty sequoia
#

the alpha fade shouldn't affect the expected collider. My workaround was to just disable raycast hit on everything and add an invisible image for the actual raycast hit that is sized to the arrow

teal viper
#

Alpha fade does.

teal viper
lofty sequoia
#

Sorry, I'm talking about how a Unity Button detects a button press. You're supposed to be able to drop in an image and it should use that image as the button. However, my button just has a lot of white space around it, and Unity is getting confused and included the alpha channel in what it detects as a press.

#

I'd like to exclude the surrounding white space from what Unity detects as a press and only use the inside arrow

alpine fjord
bronze otter
bronze otter
#

btw if you're using a button component, it will take your image as a hitbox, you can't edit it. If you want to edit your button, you have to use a custom collider

dreamy thistle
#

if im working on a project with a friend and i check in my changes but they cant see what ive done what is the problem?

astral citrus
gilded sinew
#

quick question, for some reason gameobjects in list Borders arent getting destroyed and removed from scene (i instantiated them in some other part of code). Borders.Count give same number as before the loop

#

here is part of code where i instantiate them

astral citrus
naive pawn
#

the list is going to still have those destroyed gameobjects

gilded sinew
#

yeah Borders is list, border is single game object

naive pawn
#

they're be invalid, but they won't just drop out of the list

gilded sinew
#

but why are they still on my scene cryKEKW

#

if i destroyed them

naive pawn
#

maybe you're looking at ones that aren't in your list 🤷

#

you can do Borders.Clear() at the end of the deletion method to clear the list

gilded sinew
#

i read that that wont solve problem, it will remove references to them but they will remain on scene

naive pawn
#

Destroy shouldve removed them from the scene; that's a separate issue

#

if you want to clear the list, you'll have to use that method afterwards

gilded sinew
#

also i change scene and go back and they still get instantiated (script is part of object which has DontDestroyOnLoad, so they definitelly arent getting removed from the list or are invalid

naive pawn
gilded sinew
#

sort of but in other parts as well for example when i change color of my borders i call it again and it just adds more borders on top of eachother,

#

Destroy(obj) doesnt work at all idk how

naive pawn
naive pawn
gilded sinew
#

my point is that Borders list keeps all members for some reason even after destroying and they stay on scene

gilded sinew
naive pawn
#

that's because that's how lists work

#

objects being in the list and objects being in the scene are separate concepts

gilded sinew
#

okay but my idea was to store each instantiated object in one list and delete them all before instantiating updated version of borders if you understand me

#

idk how to keep track of all instantiated objects otherwise

naive pawn
#

sure, but you'll have to clear the list after deleting them

#

you have 2 separate issues right now, you're conflating them

#

is Borders getting reassigned anywhere?

gilded sinew
#

no. give me as econd to check something

naive pawn
#

actually, probably more useful: does Border.Count align with the amount of borders you see in the scene?

naive pawn
#

try logging obj.name, see if those line up with what you're expecting to be destroyed

gilded sinew
#

good call

#

btw even .Clear didnt help kekw

#

its like i am losing reference the the object i am trying to destroy

#

maybe if i put it as parent of some object and destroy all childrens of it

naive pawn
#

sure, that could work

gilded sinew
#

will try tmrw i am dead tired Harold1

cosmic dagger
#

You need to remove them from the list first, then destroy them. You can't remove a reference from the list if it's already destroyed . . .

faint osprey
#

im using a distant joint as a rope swing however its causing gravity to not affect my player at all and i dont know why. like instead of swing it just very slowly move to the bottom of the joint

#

ok its affecting it now slightly

#

if i swing the player up it will fall down but then as soon as the distance joint2d constrains it from falling further all that vertical movement is just killed instead of converting into a swing

naive pawn
faint osprey
naive pawn
#

you're probably setting the velocity or position somewhere, and not letting momentum/gravity handle that

faint osprey
naive pawn
#

can't really help with code when we don't see the code...

faint osprey
#
    public void SetInMove(float newMove)
    {
        if ((newMove > 0 && m_isCrouchedNearLedgeRight) || (newMove < 0 && m_isCrouchedNearLedgeLeft))
        {
            // Prevent movement if crouched and near a ledge
            return;
        }
        m_InMove = newMove;
    }```
thats what im using for movement
#

apart from that im not sure

#

oh wait hang on

faint osprey
# naive pawn can't really help with code when we don't see the code...
    {
        while (m_RB.linearVelocityY > m_apexTrigger)
        {
            yield return null;
        }

        m_inApex = true;

        m_RB.gravityScale = m_RB.gravityScale * m_apexGravityScale;

        if (m_currentScene > 2 || m_hasCompletedTutorial)
        {
            m_MoveSpeed = m_MoveSpeed * m_apexSpeedBoost;
        }

        while (m_RB.linearVelocityY > -m_apexTrigger)
        {
            yield return null;
        }

        m_inApex = false;

        if (m_currentScene > 2 || m_hasCompletedTutorial)
        {
            m_MoveSpeed = m_MoveSpeed / m_apexSpeedBoost;
        }

        m_RB.gravityScale = m_normalGravityScale;
    }```
maybe my jump apex handler is affecting it
wintry quarry
#

it's only setting the m_MoveSpeed variable

faint osprey
#

oh shoot u right

#

ah

#

i think i see the issue

#
    {
        m_RB.linearVelocityX = m_MoveSpeed * m_InMove;
    }```
#

when im not pressing keys

#

me velocity x

#

will always be 0

wintry quarry
#

yep

faint osprey
#

so disable fixed update while in rope swing?

wintry quarry
#

well you can't disable FixedUpdate without disabling the script. But you can put this particular code inside an if statement

faint osprey
#

yeah thats what i meant

faint osprey
#
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)```
why am i getting this error
#

i subscribe to an action on the player

#

but when the scene is unloaded

#

and i press the button which invokes the action

#

i get that

#

ok well its randomly started working

#

wait no

#

some times it works some times it gives me the error

#

weird

small gyro
#

I added an Animation Event. I am unsure how to tell it to look for a function like before? Is there a new way of doing this?

ember tangle
#

if scriptable object Weapon inherits from Item how do I get Weapon weapon out of List<Item> items?

small gyro
#

I am unsure if you are talking to me. But if you are heres a image of what I am talking about just in case.

#

I did end up figuring it out. Having () broke it.

teal viper
rich adder
#
foreach(Item in items) {
  if(item is Weapon weapon){
//found a weapon
naive pawn
ember tangle
naive pawn
teal viper
naive pawn
#

this may be a case of https://xyproblem.info, so you might want to elaborate on what you're trying to achieve here so we can give proper advice specific to your situation

#

for example, if you're making a sorting system for an inventory, it would definitely make sense to have this kind of check

ember tangle
#

I have it set up so that there is an enum that is used as an index for the List<Item> inventory, making 0 - 9 equipment slots and the rest the general inventory of an entity. Once an item passes a check it can be equipped into one of those slots or used as a consumable, and at that point the polymorphism matters. It made a lot of the code I did way more simple and with fewer lines, but its mostly so I don't have to look at a bunch of unused attributes when I make a scriptable object.

#

so a potion doesnt have a projectile type or an armor class.

naive pawn
#

couldn't you just have an enum ItemType for Consumable, Equippable, Weapon etc and just check that instead of checking what class it is?

#

that would make it much easier to make new item classes, as you'd just have to mark the item as that type

#

you might not always be able to extend existing classes even for items of the same type

#

for example, Weapon right now seems to be a firearm, but a melee weapon wouldn't have projectile info, so you wouldn't be able to extend it
of course you could use classes to specify that type, ie make Weapon only have like, cooldown, but weapons as a whole are kinda too diverse to have anything else, and that isn't really meaningful to make a whole class for

#

(although, cooldown would probably be something items have in general...)

rich harness
#

does anyone have a super efficient awesome way for playing png sequences un unity, with transparencies?

im currently preloading all of the images and then iterating through them on a rawimage.texture

private void FixedUpdate()
{
    if (isPlayingSequence && overlayFrames.Count > 0)
    {
        float currentTime = Time.time;
        if (currentTime >= nextFrameTime)
        {
            overlayRawImage.texture = overlayFrames[currentFrameIndex];
            nextFrameTime = currentTime + frameInterval;

            // Move to the next frame
            currentFrameIndex++;

            if(currentFrameIndex == 2)
            {
                SetRawImageAlpha(1f); // Make the overlay visible
            }

            // Check if the sequence is complete
            if (currentFrameIndex >= overlayFrames.Count)
            {
                StopSequence(); // Stop and clean up
            }
        }
    }
}

public IEnumerator LoadSequence(string imagePathPrefix)
{
    overlayFrames.Clear();
    currentFrameIndex = 0;

    int frameIndex = 0; // Starting frame index
    Texture2D frame;
    Debug.Log($"Loading overlay frames from {imagePathPrefix}{frameIndex:D3}...");

    while ((frame = Resources.Load<Texture2D>($"{imagePathPrefix}{frameIndex:D3}")) != null)
    {
        overlayFrames.Add(frame);
        frameIndex++;
    }

    if (overlayFrames.Count > 0)
    {
        Debug.Log($"Loaded {overlayFrames.Count} frames for sequence {imagePathPrefix}.");
    }
    else
    {
        Debug.LogError("No overlay frames found in Resources.");
    }

    yield return null;
}

public void PlaySequence()
{
    if (overlayFrames.Count > 0)
    {
        isPlayingSequence = true;
        currentFrameIndex = 0;
        nextFrameTime = Time.time + frameInterval;
        EnableOverlay();
    }
    else
    {
        Debug.LogError("Cannot play sequence. No frames loaded.");
    }
}
#

im looking into going with an atlas and a shader to do it instead currently
the assets are too big to stitch into a single sprite sheet

rich harness
#

im currently trying that actually. just converted the sequence to sprites and dragged them in

clever idol
#

I have looked it over thousends of times but it doesnt work for some reaons:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public float jumpForce = 5f; // Hoe hoog de speler omhoog gaat
public float moveSpeed = 5f; // Hoe snel de speler naar rechts gaat
private Rigidbody2D rb;

void Start()
{
    // De Rigidbody2D van de speler ophalen
    rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    // Check of op de spatiebalk is gedrukt
    if (Input.GetButtonDown("Jump"))
    {
        // De huidige snelheid resetten zodat de speler gelijk omhoog gaat
        rb.velocity = Vector2.zero;

        // Kracht naar boven toevoegen
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }

    // Automatisch naar rechts bewegen
    rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
}

}

keen dew
#

You're immediately overwriting the velocity on the last line which undoes everything that the jump code does.

#

The code looks like it's written by ChatGPT. Look up a basic movement tutorial, there are a lot of them

nocturne kayak
#

Hey, i'm following a tutorial on state machines, and i've just implemented it, but i can't really call a SwitchState method from a button or anything of the sort

#

what am i doing wrong here?

#

(Oh yeah i forgot i made the googoogaagaa method just to see if i could actually call anything from this one)

teal viper
nocturne kayak
#

Alright

#

That makes sense

#

I don't know if that'd be considered a hacky solution, but what if i implemented an enum with all my states and switched the state machine through that?

teal viper
nocturne kayak
#

I'm having some trouble following, would that just boil down to building a bunc of SwitchToXState() methods?

void notch
teal viper
hexed terrace
#

for a start, your Visual Studio isn't configured... do that first. See the bot msg below

#

!vs

eternal falconBOT
#
Visual Studio guide

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

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

languid spire
#

'wrong' tells us nothing. You will need to provide actual details

hexed terrace
#

We can see that

languid spire
#

and type in full sentences

hexed terrace
#

I've spotted 1 error .. which Unity will tell you what it is and where it is. But, configure your Visual Studio before continuing

#

Once you've sorted your VS out, IT will tell you what and where the error is

#

ok, that's irrelevant

#

I can SEE it is not configured

#

!vs

eternal falconBOT
#
Visual Studio guide

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

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

hexed terrace
#

READ the guide linked twice now.

hexed terrace
#

a beginner at reading?

#

don't yet know what?

#

All you have to do is click the link, read, and follow the guide. ¯_(ツ)_/¯

#

Yep.

#

Clicking the link takes you directly to a specific section on that page.

languid spire
#

what do you think this says?

hexed terrace
#

READ 😄

#

Being "new" to Unity isn't relevant. You just have to read a guide and follow it..

languid spire
#

then probably game dev is not for you

modest dust
#

||Don't listen, read||

naive pawn
#

unity doesn't use c++

languid spire
#

there are more steps to follow, do them all

hexed terrace
naive pawn
#

if you don't properly configure your ide, it won't be effective as an actual ide, it'll just be a text editor

#

a properly configured ide highlights errors and provides autocomplete

hexed terrace
#

you scrolled up, instead of starting from where the link took you and scrolling down

naive pawn
#

it'll make your experience much better

hexed terrace
#

40 mins after first being told about them 😄

burnt vapor
#

I would love to hear what you have actually done in terms of steps

frosty hound
#

If you're just going to talk nonsense for an hour, please stop posting.

burnt vapor
#

You have been given help for the past two hours and all you have been able to do is respond with lazy, uninformative answers

#

Either give clear answers that people can actually use, or don't bother asking for help

#

I want you to properly explain what you did in regards to configuring your editor. Explain the steps and show that you have done them

#

If you truly followed all the steps, then it should all match

#

Then show it

#

I don't see the point with this back and forth bickering, either post your process so people can spot the problem or nobody is going to help you

fickle plume
#

!ban 349901428912816139 Ignorant stubborn child

eternal falconBOT
#

dynoSuccess highvoltage2011 was banned.

fickle plume
#

was going to mute them before insults...

real thunder
#

So I recently figured that a parent having a Rigidbody2D soaking up all OnTriggerEnter2D and OnCollisionEnter2D events onto itself
Scripts on child GameObjects having colliders seem to ignore those iirc
That's pretty annoying because I seem to be having to make a huge if-else(or rather switch) thingie on the main parent object to figure out what exactly have collided with which exact subcollider, because I want different responses for different colliders
What do I better do?

#

Also it seems like changing a Layer of those child GameObjects having colliders doing nothing in terms of collisions, it's just changing their rendering layer, I am having to tune their colliders Layer overrides because they seem to obey the parent layer

#

this is so confusing, I feel like it was poorly designed

frail hawk
#

well it will be called on the gameobject with the rb

real thunder
#

the biggest issue seems to be is about trigger entering
because it only returns a second collider, but not the receiver

#

anyway it's not what bothering me but the fact I am having to do a big if else thingie so the script figure out what are we colliding with

#

I guess there is no workaround there

frail hawk
#

so you just want to know on which child object the collision happened or

real thunder
#

yeah that's... still same amount if switches really

#

I tuned my layers in a way that there are no unwanted collisions

#

well, maybe it's better optimization wise to have one big if else script instead of bunch of tiny ones on each subcollider...

#

How can we understand anything from this ambiguous screenshot and description

#

I might assume you want to freeze rotation on the player rigidbody if he is using that component even

rocky canyon
#
  1. rotation code is broken
  2. animations are broken
  3. rig is missing/broken
  4. pivot is broken
shell matrix
#

I can't figure out how to fix this."

real thunder
#

Have you wrote your code of moving yourself or at least do you understand how it works?

shell matrix
real thunder
#

so what do you use to move the character?

shell matrix
#

float forward = Input.GetAxis("Vertical");
float right = Input.GetAxis("Horizontal");

languid spire
#

that does not move anything

shell matrix
#

this is all code

languid spire
#

point is, as you could not answer the question, you do not understand your own code

shell matrix
languid spire
#

no you did not

shell matrix
#

if you are referring to the movement animation it is written below in the code I created a variable in the animator which I set as in , I created the transition and when the character is in idle state it takes the value 1 i.e. true and vice versa

#

Do you want me to explain everything with direction and speed?

real thunder
#

I would rather want you to explain why did you thought that spinning a character getting mouse movement is a good idea

#

that's kinda... insane

real thunder
# shell matrix this is all code

You should probably watch a tutorial or two how to make player movements using a character controller or a rigidbody
I don't feel like you have a grasp on what are you doing given your responses and the code itself
You should completely rewrite that
Btw you can make animator boolean params, you don't have to use 0 or 1 integer

twilit ocean
#

Hey, I'm a newbie on dev and was thinking about how to approach some topics using logic.

For example, I wanted to make a pixel filter with outlines. How do I even start such task? Do I go learn all I can about how does a shader work and start one from the ground? There are some guides on it but the ones that do explain what I wanted to hear already presume I have a built shader.

frosty hound
#

Logical thing would be to have someone else solve it by using something like the very capable All-In-One Sprite shader pack on the asset store so you can focus on making your game.

twilit ocean
real thunder
#

Asking because I am clueless, what is the "pixel filter with outlines"?

#

The shader making stuff pixelated and having an outline, I figured

polar acorn
twilit ocean
real thunder
#

I hate shaders... I lack comprehensive knowledge about how to make them, but given what I know I would advice to not trying to make ones yourself
unless you really really have to

alpine fjord
twilit ocean
twilit ocean
real thunder
#

I dunno what are you talking about, I had an impression that it's all about sprite graphics

cosmic dagger
real thunder
#

I tried and it didn't work out well 🤷‍♂️
That's definitely not one of the things you should do when you are starting out

willow shoal
#

Hi. how to change gravity from script without using rigidbody

polar acorn
real thunder
#

do you mean change the constant gravity variable or what

cosmic dagger
willow shoal
#

so i cant? without this

polar acorn
#

Well, Gravity as a Unity-defined concept only applies to Rigidbodies.

#

If you aren't using them, you'd need to write your own gravity

willow shoal
#

my player change gravity after like 0.5sec when he is on block.

real thunder
polar acorn
polar acorn
real thunder
polar acorn
willow shoal
#

i try use gravity after click button using constant force or gravity in inspector

#

with script

polar acorn
#

If you're using SimpleMove and want to change the gravity, the solution is don't use SimpleMove

willow shoal
#

oh okey

real thunder
willow shoal
#

yes and no

real thunder
#

._.

willow shoal
#

i try some options

#

: /

polar acorn
willow shoal
#

"character controler"

real thunder
#

Character Controller is a component you put on your GameObject, player I guess

willow shoal
#

but it work not like i want

real thunder
#

it's an alternative to a rigidbody

willow shoal
#

this is it?

#

or somethink like this?

#

i found this

#

you guys mean with (CharacterController)

cosmic dagger
#

wow, this is ancient. that's unity script . . .

polar acorn
#

This isn't C#

willow shoal
#

oh

real thunder
#

this thing?

#

I made my first FPS game using it but it's kinda lame, no physics interactions whatsoever

#

well, no realistic ones

#

no built in inertia, and you push rigidbodies like you have infinite mass

willow shoal
#

you can't move the entire object "probably"

#

using only character controler

real thunder
#

wdym

willow shoal
#

or i say wrong

polar acorn
willow shoal
#

using (for example) animation on button in inspector you cant move everyblock

#

from hierarchy

#

sorry for bad english

real thunder
#

yeah I figured there should be some language misunderstanding

willow shoal
#

xd

real thunder
#

I still don't understand what do you want to say however ><

willow shoal
#

i use for button space animation move

#

but if i move somethink in inspector

#

i move only one block

#

character controler this green block (these lines) when u have box colider

#

i need move all

#

(player)

#

and im stuck so ;/ i ask here how to fix this

real thunder
#

do you say "block" wanting to say a "collider"?

willow shoal
#

for move like i want

willow shoal
#

yes

#

sry

real thunder
#

Usually, if you have a child GameObjects in the hierarchy
when you move parent, all childs move along

willow shoal
#

but I change the position the same.

#

if i change "y"

real thunder
#

the only exception I know is when a child having a "Rigidbody" component
this case if you need it you have to set it to be kinematic

willow shoal
#

in animation same

real thunder
#

and if that's a character controller, well, you are not supposed to have child character controllers

#

it should be on the main parent object

real thunder
#

it's dynamic kinematic or static

#

as far as I remember

willow shoal
#

where it is? in inspector or i need in script

real thunder
#

In inspector

willow shoal
#

or dynamic

real thunder
#

Body Type

#

like, upper parameter

#

How your character hierarchy looks like anyway?

#

I mean the player

#

because I have feelings like you don't need several rigidbodies

willow shoal
#

it work same with kinematic

#

;/

#

i have just rightbody with kinematic on

#

but work same

real thunder
#

can you formulate
what do you want to do
what do you do
and what is going wrong

willow shoal
#

wait i need ask

#

what if there is an option such that it adds +1 all the time in transform “y” and when I change the gravitations it adds -1 it will fix it

#

in c# is option like this?

#

or no

real thunder
#

it's not about C# it's about Unity and yeah you can just

#

ignore all that rigidbody charactercontroller stuff and make gravity manually

#

assuming you don't need to interact with anything

#

using colliders

willow shoal
#

i will try

real thunder
#

that is a niche case tho

#

what your gameplay even is

willow shoal
#

i have copy of geometry dash but difrent and i need change gravity player

#

(3d gd game)

#

i have some plans

#

and i need it

real thunder
#

well there are indeed colliders and you have to use a rigidbody

willow shoal
#

u give me idea

real thunder
#

however it would be easier to uncheck rigidbody using a gravity

#

and emulate it yourself

#
    {
        if (body.velocity.y >= 0)
        {
            body.velocity -= new Vector2(0, jumpConfig.upGravity * Time.fixedDeltaTime);
        }
        else
        {
            body.velocity -= new Vector2(0, jumpConfig.downGravity * Time.fixedDeltaTime);
        }
    }```
#

look, that's my method in the FixedUpdate loop for a sloppy platformer I made

#

you should put something like that into FixedUpdate

#

basically multipication of deltatime passed on your wanted acceleration summed up with current rigidbody velocity

willow shoal
#

i will try this

real thunder
#

yeah just not copy the code but copy the principle

#

wait... geometry dash

#

straight lines.. I am not sure it even uses acceleration

#

maybe it's just gives constant velocity up/down

willow shoal
#

i try now change transform "y" in animation after click and it work but my player cant move

real thunder
#

what do you mean by an animation

willow shoal
#

on trigger

#

animation after click button

#

change from this to this

real thunder
#

I am still not understanding what is going on your end well and gtg, sorry

willow shoal
#

YES I DID IT

#

i add game object

#

and after this block to this

#

move player to block and change gravity on animation to gameobject

#

thanks for help ❤️

little raft
#

so i am trying to make a build sistem based on a database here s the thing:

#

sorry

#

i try to make the transparent prefab to follow the mouse

#

but i just can t think of a reliable way

#

(my code is build from 3 diffrent tutorials if you want i put the links in)

#

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

public class InputManager : MonoBehaviour
{
[SerializeField]
private Camera sceneCamera;
private Vector3 lastPosition;
[SerializeField]
public RaycastHit hit;
[SerializeField]
private LayerMask placementLayermask;
public event Action OnClicked, OnExit;
private void Update()
{
if(Input.GetMouseButtonDown(0))
OnClicked?.Invoke();
if(Input.GetKeyDown(KeyCode.Escape))
OnExit?.Invoke();
}
public bool IsPointerOverUI()
=> EventSystem.current.IsPointerOverGameObject();
public Vector3 SelectMapPosition()
{
Vector3 mousePos =Input.mousePosition;
mousePos.z=sceneCamera.nearClipPlane;
Ray ray=sceneCamera.ScreenPointToRay(mousePos);

    if(Physics.Raycast(ray,out hit,100,placementLayermask))
    {
        lastPosition =hit.point;
    }
    return lastPosition;
}   

}

#

i understand that i need to somehow put a refference in the update function

languid spire
#

!code, Do not use screenshots unless asked. Do not post large blocks of code directly into the chat

eternal falconBOT
little raft
#

so i give you the url in chat? sorry i am new

willow shoal
#

Use this (```)

little raft
#
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlaceingObj : MonoBehaviour
{
    [SerializeField]
    private InputManager InputManager;
    [SerializeField]
    private DatabaseSO database;
    private int selectedObjectIndex=-1;

    
    void Start()
    {
         StopPlacement();
    }
    public void StartPlacement(int ID)
    {
        StopPlacement();
        selectedObjectIndex =database.objectsData.FindIndex(data => data.ID==ID);
        InputManager.OnClicked += PlaceStructure;
        InputManager.OnExit += StopPlacement;
       
    }
    private void TransparetFlow()
    {
        GameObject newTransparentObject = Instantiate(database.objectsData[selectedObjectIndex].TransparentPrefab);
        newTransparentObject.transform.position=InputManager.SelectMapPosition();
    }
    private void PlaceStructure()
    {
        
        GameObject newObject = Instantiate(database.objectsData[selectedObjectIndex].Prefab);
        newObject.transform.position=InputManager.SelectMapPosition();
    }
     private void StopPlacement()
    {
       
        selectedObjectIndex =-1;
        
       
        InputManager.OnClicked -= PlaceStructure;
        InputManager.OnExit -= StopPlacement;
       
       
    }
    // Update is called once per frame
    void Update()
    {
        InputManager.OnClicked += TransparetFlow;
        if(selectedObjectIndex <0)
            return;
    }
}
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class InputManager : MonoBehaviour
{
    [SerializeField]
    private Camera sceneCamera;
    private Vector3 lastPosition;
    [SerializeField]
    public  RaycastHit hit;
    [SerializeField]
    private LayerMask placementLayermask;
    public event Action OnClicked, OnExit;
    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
            OnClicked?.Invoke();
        if(Input.GetKeyDown(KeyCode.Escape))
            OnExit?.Invoke();
    }
    public bool IsPointerOverUI()
        => EventSystem.current.IsPointerOverGameObject();
    public Vector3 SelectMapPosition()
    {
        Vector3 mousePos =Input.mousePosition;
        mousePos.z=sceneCamera.nearClipPlane;
        Ray ray=sceneCamera.ScreenPointToRay(mousePos);
       
        if(Physics.Raycast(ray,out hit,100,placementLayermask))
        {
            lastPosition =hit.point;
        }
        return lastPosition;
    }   
}
velvet pagoda
#

guys this code doesn't work and IDK why

little raft
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu]
public class DatabaseSO : ScriptableObject
{
    public List<ObjectData> objectsData;
}
[Serializable]
public class ObjectData
{
    [field: SerializeField]
    public string Name { get; private set; }
    [field: SerializeField]
    public int ID { get; private set; }
    [field: SerializeField]
    public Vector2Int Size { get; private set; } = Vector2Int.one;
    [field: SerializeField] 
    public GameObject Prefab { get; private set; }
    [field: SerializeField] 
    public GameObject TransparentPrefab { get; private set; }
}
#

i want to move the transparent prefab along with the position of the mouse

#

i understand that i need to put a reference in the update

#

but i get this error

stable nebula
#

Hello

#

Im a noob

polar acorn
# little raft

You're trying to get an index from a collection that is either negative, or larger than the collection's size

little raft
#

wait wait i modified sth

polar acorn
little raft
#
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlaceingObj : MonoBehaviour
{
    [SerializeField]
    private InputManager InputManager;
    private transparentMovement transparentMovement;
    [SerializeField]
    private DatabaseSO database;
    private int selectedObjectIndex=-1;

    
    void Start()
    {
         StopPlacement();
    }
    public void StartPlacement(int ID)
    {
        StopPlacement();
        selectedObjectIndex =database.objectsData.FindIndex(data => data.ID==ID);
        InputManager.OnClicked += PlaceStructure;
        InputManager.OnClicked += FixedUpdate;
        InputManager.OnExit += StopPlacement;
       
    }
    private void PlaceStructure()
    {
        
        GameObject newObject = Instantiate(database.objectsData[selectedObjectIndex].Prefab);
        newObject.transform.position=InputManager.SelectMapPosition();
    }
    void FixedUpdate()
    {
        database.objectsData[selectedObjectIndex].TransparentPrefab.transform.position=InputManager.SelectMapPosition();
    }
     private void StopPlacement()
    {
       
        selectedObjectIndex =-1;
        
       
        InputManager.OnClicked -= PlaceStructure;
        InputManager.OnExit -= StopPlacement;
       
       
    }
    // Update is called once per frame
    
    void Update()
    {
        if(selectedObjectIndex <0)
            return;
    }
}
little raft
polar acorn
#

What line?

little raft
#

i don t know how to debug otherwise than hitting play in unity

polar acorn
#

Do you know how to click on something and read it

little raft
#

damn sorry i didn t saw where it was written

#

line 38

polar acorn
#

which is...

little raft
little raft
polar acorn
# little raft

You will notice that since you did not post the !code to a bin site, I have no line numbers

eternal falconBOT
little raft
#
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlaceingObj : MonoBehaviour
{
    [SerializeField]
    private InputManager InputManager;
    private transparentMovement transparentMovement;
    [SerializeField]
    private DatabaseSO database;
    private int selectedObjectIndex=-1;

    
    void Start()
    {
         StopPlacement();
    }
    public void StartPlacement(int ID)
    {
        StopPlacement();
        selectedObjectIndex =database.objectsData.FindIndex(data => data.ID==ID);
        InputManager.OnClicked += PlaceStructure;
        InputManager.OnClicked += FixedUpdate;
        InputManager.OnExit += StopPlacement;
       
    }
    private void PlaceStructure()
    {
        
        GameObject newObject = Instantiate(database.objectsData[selectedObjectIndex].Prefab);
        newObject.transform.position=InputManager.SelectMapPosition();
    }
    void FixedUpdate()
    {
       //38 database.objectsData[selectedObjectIndex].TransparentPrefab.transform.position=InputManager.SelectMapPosition();
    }
     private void StopPlacement()
    {
       
        selectedObjectIndex =-1;
        
       
        InputManager.OnClicked -= PlaceStructure;
        InputManager.OnExit -= StopPlacement;
       
       
    }
    // Update is called once per frame
    
    void Update()
    {
        if(selectedObjectIndex <0)
            return;
    }
}

little raft
polar acorn
#

Use a bin site like the bot says

little raft
#

but i will try

polar acorn
north kiln
#

Don't use the first link as it's broken

little raft
rocky canyon
# little raft i don t know how to debug otherwise than hitting play in unity
    void Start()
    {
        Debug.Log($"This script is attached to: {gameObject.name}");
        Debug.Log(privateFloat);
        Debug.Log($"privateFloat: {privateFloat}");
    }``` `Debug.Log` simplest way to debug, you leave yourself messages and log script values, basically leaving little breadcrumbs to see what does and what doesn't run, when and how u expect them to..
north kiln
#

There is nothing in FixedUpdate to protect against invalid indices

#

There is a partial check in Update that does absolutely nothing

little raft
north kiln
little raft
#

ok now i understand the error but i still don t know how to do my thing

eternal stag
#

hey is "private" used so people cant hack your game through the inspector?

little raft
runic lance
eternal stag
#

alright thanks for the help

versed cove
#

Hi! I have an idea to make a cutting tool that can cut through walls, who knows the best method for that? Should I use some unity asset already made, or should i go and code this myself? Here's a video for concept..

Yes.. I know the way im doing this is incredibly stupid but it was just a test idea.

#

Also totally not copyrighted assets

#

I dont know how or of any slicers that could follow a custom path

#

And not just cut in half

frosty hound
#

@stuck monolith You've already been directed before to use !collab

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

stuck monolith
polar acorn
lofty sequoia
#

is there a way to check if a button is being rendered or not?
I see it has a canvas renderer, but not a regular renderer on it...and CanvasRenderer does not inherit from Renderer for some stupid reason.

raw loom
#

anyone have an idea on how to make the ball less floaty? i tried increasing mass but it didn't help :/

keen dew
#

Gravity famously affects all objects the same regardless of their mass

#

It looks like the board is about 30 meters tall. That's how it would look like if a 1-meter ball goes up and down 30 meters. Make the whole thing smaller and it'll act more like a realistically sized pinball table would

jade zenith
#

Does anyone know why my visual studio refuses to open my script? I can't open it via the component, the asset png, force opening it from file explorer, i've checked and double checked that its in my preferred external tools, regenerated my project files, deleted and remade my game object, and can't seem to open the script

exotic turtle
#

I'm making a 3d game but I can't figure out how to constrain the camera so I can't do vertical 360s. I have tried Mathf.Clamp in every way I can imagine.