#πŸ’»β”ƒcode-beginner

1 messages Β· Page 83 of 1

summer stump
#

^ This is about the fourth time we've told you that

dense root
#

Okay I readded it but it still doesn't want to shoot

#

Alright I'll try Impulse

wintry quarry
#

because the force is too low and not using Impulse

normal slate
#

show us the code again

summer stump
#

make it Impulse and set thrust to 100

normal slate
#

once you are done

summer stump
normal slate
#
public class PlayerControls : MonoBehaviour
{
    public float speed = 200.0f;
    private Rigidbody2D rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        rb.interpolation = RigidbodyInterpolation2D.Interpolate;
    }
    void Update()
    {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePos.z = transform.position.z;
        Vector2 direction = mousePos - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        angle -= 90f;
        transform.rotation = Quaternion.Euler(new Vector3(0,0,angle));


        float hInput = Input.GetAxisRaw("Horizontal");
        float vInput = Input.GetAxisRaw("Vertical");
        if (Mathf.Abs(hInput) > 0 || Mathf.Abs(vInput) > 0)
        {
            Vector2 direction2 = new Vector2(hInput, vInput).normalized;
            Vector2 movement = direction2 * speed * Time.fixedDeltaTime;
            rb.velocity = movement;
        }
        else
        {
            rb.velocity = Vector2.zero;
            rb.angularVelocity = 0f;
        }
    }
#

can you look at this and see if I can improve this?

#

is it correct to use velocity with player movement?

wintry quarry
normal slate
#

but I want it to move not based on framerate though

wintry quarry
#

velocity already handles that

normal slate
#

really?

#

oh weird

wintry quarry
#

Yes really

normal slate
#

okay thanks

wintry quarry
#

your velocity is X m/s

#

not X / 50 arbitrarily

normal slate
#

that sounds about right now that I think about it

dense root
wintry quarry
summer stump
dense root
#

Oh

summer stump
dense root
#

What do I do instead?

#

Ahh I didn't see that sorry

normal slate
#

new Vector2(0,1)

summer stump
#

Oh, well if it works it works

wintry quarry
# dense root

why does your spawner have a Rigidbody on it at all? the ball rigidbodies are what you care about having gravity scale set to 0, not the spawner

normal slate
#

should be the same thing

summer stump
normal slate
#

true i guess use case would be if you want to consider the current object's rotation as well.

wintry quarry
#

You set gravity scale to 0 on the spawner. It needs to be set on the ball prefab

dense root
#

ohhhh

wintry quarry
#

The spawner also doesn't need a Rigidbody2D at all

dense root
#

Thank you

normal slate
#

so i am confused exactly what rigidbody2d does then? I put it on my character because I was told it helps with collisions somehow can you help explain please.

wintry quarry
ivory bobcat
#

It's a component that allows the object to simulate rigidbody in 2d

wintry quarry
#

When you have one, you are a 2D physics object

#

if you don't have one, you aren't one (or at least not one that can move via the physics sim)

normal slate
#

wait so can not apply velocity to one without it?

summer stump
normal slate
#

what do you mean by move via the physics sim is it with the collisions?

wintry quarry
wintry quarry
normal slate
#

ah okay

wintry quarry
#

otherwise you have to move everything yourself

ivory bobcat
#

You get the whole rigidbody physics bundle (not fake game physics)

normal slate
#

like actually using the transform.position to set it right?

wintry quarry
normal slate
#

ah okay

#

cool thanks

amber spruce
#

this is my first real attempt to make a character controller by myself without a tutorial

bright nexus
#

Hello, I have set up an extremely simple gravity system subtracting velocity from the players y position every frame. My script is causing my player to move down extremely fast in the first few seconds I start the game. I have added a clamp to my fall speed (in which the velocity can only barely go over according to the console), yet my player can still go fast enough to move through the floor. I am beginning to think this is a problem with my groundcheck although I don't have a clue what it is. I am looking for some help so I can get things working properly. Thank you https://paste.myst.rs/hi3j0h3a

mint dove
amber spruce
desert temple
#

I'm having some trouble setting up an exit button for my student project, and I've been following multiple tutorials, so I suspect I'm just doing something wrong.

mint dove
amber spruce
mint dove
#

you can use enums to make player states like idle, walking, running etc. than you can use the state to jump, walk etc.

amber spruce
#

im still not following sorry if im just being dumb right now

lament agate
#

Hi guys, I have an issue where the prefabs aren't saving the game object I'm using in the variable slot, also when I put the script on my object it gives me the wrong script name (Sci Fi Warrior CON in this case) but it is using the correct script still but I'm not sure if there's another issue that's causing it, not sure what to do at all

abstract finch
#

What is the term for the :Bullet part?
public class HomingBullet : Bullet

lament agate
lament agate
#

No worries πŸ™‚

amber spruce
lament agate
amber spruce
lament agate
amber spruce
#

alright thanks

#

for if statements how do i have it so it checks for this or this

modest barn
amber spruce
#

thanks

#

so i have a IsGrounded function

public bool IsGrounded()
{
    return Physics2D.BoxCast(m_Coll.bounds.center, m_Coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}

how would i check to see if the player lands so like if they wherent grounded a second ago

dark laurel
#
private bool _isGrounded = true;
private void Jump()
{
  // apply force upward
  _isGrounded = false;
}

private void Update()
{
  if (!_isGrounded && IsGrounded())
  {
    Debug.Log("Major Tom to Ground Control, I'm feeling very still");
    _isGrounded = true;
  }
}
round scaffold
#

Hey I wanna make an inventory system where all the items compose of weapons, abilities and, consumables, would it be better to use scriptable objects, class inheritance, or interfaces for the items?

round scaffold
#

i agree

dark laurel
#

ScriptableObjects to hold your data points (int weight, Sprite icon etc).

Polymorphism to reduce copy and paste code (int id, string name).

Interfaces to make interactions easier. (if (InventoryItem is IStackable item) item.StackIt(); )

cosmic dagger
dark laurel
#

But if you're asking this question - start extremely simple and try ScriptableObjects first. Polymorphism and Interfaces is gonna getcha and not really advance "making fun shit" that quickly.. you'll just be staring at code and documentation without really seeing or understanding why you're doing what you're doing. πŸ™‚

median hound
#

how do i set a sting to a blank value? creating the line " private string ""; " gives me errors

dark laurel
#

you need to name it first

#
private string myString = "";
amber spruce
#
IEnumerator JumpDelay()
{
    yield return new WaitForSeconds(0.01f);
    OnLanding();
    Debug.Log("JumpDelay");
}
private void Update()
{
    Move();
    Crouch();
    Sprint();
    Jump();
    JumpDelay();
}

i never get the debug

#

anyone know why

dark laurel
#

or better

private string myString = string.Empty;
median hound
#

tnx

dark laurel
amber spruce
#

i keep forgeting that lol

#

thank you so much

cosmic dagger
amber spruce
#

how do i have it so it doesnt run it again till the current one finishes

#

i got it

summer stump
amber spruce
#

just had to place the iniitial one in the start function and have it inside the coroutine start itself

round scaffold
amber spruce
#

i just found my first bug that is gonna just be a feature lol if you try and double jump instantly after landing from a previous jump you can only jump once auto fatigue lets go

modest barn
#

"... your game crashes in the first 20 seconds and force-restarts my PC..."
"tired programmer: GAME FEATURE, high-stakes permanently-enabled speedrun mode ;)"

#

Quick question. With the TextMeshPro Dropdown object, with the onValueChanged() method that it automatically calls when, you guessed it, the selection changes. It is supposed to pass an integer that represents the current index of the choice selected, but that doesn't seem to be working for me. Below is a screenshot of what the Inspector window contains on the Dropdown object.

median hound
#

when i run this it dosent output anything?

#

ive never used inputs so i have no clue on what might the issue be

modest barn
# modest barn

Here the int is shown in the Inspector window but it always remains on 0, no matter what is selected. I followed a tutorial and this is exactly what they had.. can someone help me out?

ivory bobcat
modest barn
#
public void OnValueChanged(int index)

I have this in my script

#

And that function is run whenever the dropdown selection changes

ivory bobcat
#

So when the value changes, it'll pass zero to the functions subscribing to the event.

#

So each object could potentially have a unique index value set in the inspector.

modest barn
#

So how can I have that value change respective to the index of the choice selected?

teal viper
static cedar
median hound
teal viper
static cedar
# modest barn Yep.

I was saying that they'll hold the same reference or intern anyways in compile time.
The equal operator will just do content equals so it doesn't say much.

ivory bobcat
cosmic dagger
# amber spruce how do i have it so it doesnt run it again till the current one finishes

an easy way is to store the coroutine in a variable. before you start the coroutine, check if the Coroutine variable is null. if so, then the coroutine is not running. when you call StartCoroutine, you assign the Coroutine variable . . .

private Coroutine _coroutine = null;

private void Start()
{
    if (_coroutine is null) _coroutine = StartCoroutine(MyCoroutine());
}

public IEnumerator MyCoroutine()
{
    yield return null;
    _coroutine = null;
}
modest barn
#

OHHH

#

I just selected the wrong thing

ivory bobcat
modest barn
#

It depends on which OnValueChanged is selected here. That's my bad.

summer stump
teal viper
#

They don't know

summer stump
#

Oh yeah, I just read further down
It says 0 references, so....

cosmic dagger
gaunt ice
#

Why you check the string in update, not log the string when you get it and check it

cosmic dagger
#

whoops, i'm late . . .

median hound
modest barn
#

Yeah, appreciate it though. I should've figured that out much sooner πŸ˜†

summer stump
median hound
gaunt ice
#

It passes a empty string when on end edit

#

The argument is not the actual text in inputfield

median hound
gaunt ice
#

Yes, this is empty and it always passes this empty string to your method

#

You have to reference the input field and get the input string

median hound
#

ah ok makes sense now, ill see what i can do

quick ruin
median hound
gaunt ice
#

Yes

summer stump
#

Oh, the visual clipping below the other?

#

This is really awful to view. Could you do a video from the computer itself instead of a phone, and show the inspector values of the two?

gaunt ice
#

It may due to floating point error when rendering in z buffer afaik, try to lift the red plane a bit higher,

quick ruin
scenic cipher
quick ruin
#

all are planes*

scenic cipher
#

Ahh, what is the shader on the object's material?

quick ruin
#

Unlit Transparent for all

summer stump
quick ruin
#

nothing is moving its happening in scene editor as well

scenic cipher
#

@quick ruin Could you try changing all of the shaders to Standard and see if it still happens? I wouldnt think it would be the shaders but I dont know what else could be causing that problem

summer stump
#

It would be nice to just see the inspectors...

quick ruin
#

I put carpet to standard and it fixed, I guess I'll use this

summer stump
#

Well, I must have been wrong then.

scenic cipher
quick ruin
#

Im very new to cameras and shaders

scenic cipher
median hound
scenic cipher
gaunt ice
#

Tmp_inputfield

scenic cipher
#

If its a TMP Input Field then use

[SerializedField] private TMP_InputField inputReference```
#

You may want to change the variable names to better suit what ever you're trying to do.

median hound
#

what is serialized field?

scenic cipher
#

It puts the variable in the inspector even if its private, its always best practice to keep variables private if possible.

median hound
#

ah ok tnx

scenic cipher
#

πŸ‘

median hound
scenic cipher
#

First of all, that code is supposed to be SerializeField and not SerializedField, my bad.
What are you trying to use as a string?

median hound
#

so im trying to use the TMP_InputField refrance as a string to compare it to other strings

scenic cipher
#

Use inputReference.text to get the text. I would recommend you to learn about components.

median hound
#

ahh ok tnx

modest barn
#

How can I remove a [SerializeField] and get the object within the script itself? New to Unity and I'm used to just draggin' and droppin' πŸ™‚

modest barn
# scenic cipher What do you mean exactly?

So currently I've got

[SerializeField] TMP_InputField plaintextInputField;

I want to remove the need for the serialized field at all and simply set TMP_InputField plaintextInputField = // Get GameObject or something like that. I'm assuming it can be done?

summer stump
#

You can check out all these ways to reference something

#

It sounds like you are wanting something more like Find, but I recommend against it
Drag and Drop is preferable. A serialized reference is very low cost and easy

modest barn
#

Why is dragging and dropping the best? Is there some practice I have to avoid?

rich adder
scenic cipher
#

If the component is on another gameobject, then just put it in the inspector with SerializeField

summer stump
modest barn
#

That's good to know. Serializing is easiest of course so I'll just roll with it πŸ™‚

rocky canyon
#

if not you have to search for it in the project one way or the other..
theres many different methods, but all are very similar and have to sift thru everything to find it

#

thats fine if u can do it only (once) like a level initialization or something.. but if you're using find methods frequently it'll slow ya down a lot.
so its easier and more performant to serialize and expose the variables and just drag and drop.. if you have some reference to it already that you can use to assign it in code there's no need.

rich adder
#

for Runtime components TryGetComponent and clever DI

cosmic dagger
scenic cipher
median hound
#

is there a way to save this? i didnt save the work and now its not respoding?

eternal needle
#

you can get a recent version of your scene back

median hound
median hound
#

do i just run that or?

rocky canyon
#

https://discussions.unity.com/t/unity-crashed-and-i-lost-almost-everything-how-to-recover-my-scene/220987

never done it b4, but seems like you could copy that file and rename it to a .unity file and thats ur scene but idk tbh, heres a post

median hound
#

ye i found a tut on yt but tnx

severe robin
#

hello, has any one used moonsharp for their project?

rocky canyon
#

b/c i is always zero so the loop runs forever b/c zero is less than 100

#

thats my guess ;D

median hound
#

ye i figured it out, forgot to add the if statement smh

acoustic berry
#

Is a Prefab able to dictate HOW it gets instantiated? As in, can it specify a list of parameters that must be provided in order to create one?

#

(at runtime this is)

eternal needle
acoustic berry
#

Does the Init method get called specifically directly after the Instantiate method? or is it one of the specially predefined ones that triggers itself on creation

#

Follow up question: Is there any risk in the time between it finishes the Instantiate method and the Init method? Any chance of a 1-frame visual-jank if im doing a size/color change?

eternal needle
eternal needle
acoustic berry
#

alright thank you. I will implement it this way

frozen mantle
#

Hey all, i seem to be having trouble with a BinarySpacePartitioning algorithm, in that i am trying to add a "room offset" parameter that gives some space between the rooms im splitting, but it seems that while it does give me more space between rooms, it's making all of the rooms smaller, which if you turn up the offset highenough, leaves empty/"zero" space rooms. I took the algorithm from a youtube tutorial, and one of the comments bought up this issue, saying that its due to how in the "makeSimpleRooms" function, the for statements are only executed (room.size.x - offset - offset) times. This means that when the offset is greater than 0, it reduces your available space by 2 * offset for both the width and height. The comment mentions that a simple fix could be to include the offset into the BinarySpacePartitioning() parameters, but I'm a bit lost on how exactly to do that. I've tired to add or multiply the dungeon size by the offset, but this still leads to microscopic rooms if the offset is high enough. Do you all have any suggestions? here are the scripts and some pics of the issue, thanks for your time.
https://gdl.space/vibibahiyo.cs , https://gdl.space/oqajizujol.cs

#

"oqajizujol" is the actual binary space partitioning algo, while "vibibahiyo" is the driver code that i stick onto the game object to run the generator with the variable parameters

frozen mantle
#

if this question is more than "beginner code" let me know

gaunt ice
#

passing minWidth+offset*2 and minHeight+offset*2 to the partitioner?

frozen mantle
frozen mantle
#

i think what i want to happen is that the algo makes the rooms first, and then seperates them out by the offset

gaunt ice
#

you can put the AABB inside "other AABB", while "other AABB"s are the output of the partitioner
then you dont need to change your algorithm

frozen mantle
#

if that makes sense

gaunt ice
#

just pass minWidth+offset (without*2) as well as height+offset
then the room's AABB will be min=output.min+(offset/2), max=output.max-(offset/2)

gaunt ice
#

fancy name of rect

#

axis-aligned bounding box

frozen mantle
#

who the heck calls em that

#

fair enough tho, i understand

gaunt ice
#

you can rotate a rect but not a AABB btw, it has to be aligned with the axis

frozen mantle
#

oh, i see, strange

frozen mantle
#

I think my algorithm is good, just that i am not implementing the offset properly

#

essentially what im picturing in my head is to split the rooms, and then seperate out their positions by my offset

gaunt ice
#

if the offset is too high than the area have to be large enough....
imagine offset=area width or height

frozen mantle
#

i think what im doing by just adding offset to the minWidth and height is just making is so that there's the proper space in between them, but that space takes up the dungeon size

frozen mantle
#

so i probably wanna find a way to increase the dungeon area too

#

so yeah, the BSP algo works

#

just that the offset i need to figure out how to properly integrate

rigid hinge
#

guys why the monitor shows in scene and doesnt show in game?

#

i tried to make a raycast but it glitched my game

this is the code:

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

public class PCInteraction : MonoBehaviour
{
    
    public Camera cam;
    public float playerActiveDistance;
    bool active = false;
    public GameObject interaction;
    public GameObject pc;
    public GameObject pausemenu;
    public GameObject bg;
    public LayerMask mask;

    private void Start()
    {
        cam = GetComponent<Camera>();
    }
    void Update()
    {
       Ray ray = new Ray(cam.transform.position, cam.transform.forward);
       Debug.DrawRay(ray.origin, ray.direction * playerActiveDistance);
       RaycastHit hitInfo;
       if (Physics.Raycast(ray, out hitInfo , playerActiveDistance, mask))
       {
            interaction.gameObject.SetActive(true);
            if(Input.GetKeyDown(KeyCode.E)){
                pc.SetActive(true); 
                interaction.SetActive(false);
                Time.timeScale = 1;
            }

            else{                 
                Time.timeScale = 1;
                interaction.SetActive(false);
            }
         }

         if(pc.activeInHierarchy == true)
        {
            Cursor.lockState = CursorLockMode.Confined;
            Cursor.visible = true;
         }
       }

}
#

and when i change the layer to default it appears and disappear when i make it interactable

frozen mantle
#

how does your culling mask look?

rigid hinge
#

ah oh it worked

#

thx

frozen mantle
#

Yeeee

fringe plover
#

My character is super slow with time.deltaTime, how to fix that?

gaunt ice
#

the unit of velocity is ms^-1, when you multiply it with time, the unit becomes ms^-1 * s=m
no need to multiply it with time

fringe plover
#

k thanks

topaz mortar
#

I'm making a database for an MMO game (that could possible have thousands of players)
The database is MySQL
I want to make an Items table, that just holds the playerId, itemId, and a list of ItemModIds
The ItemMods table will then hold the item stats (name, dmg, armor, level requirement, ...) each mod has it's unique Id to reference

  1. Would it be better to make a 3rd table that holds just ItemId and ModId that stores all the mods for each item
  2. Or would it be better to add more columns in my Item table so that table can have all the ModIds

1 would reduce the columns in my Item table but the 3rd table would become HUGE, having to store several rows of mods for each item
2 would reduce the amount of rows in my database, but my Items table would hold a much larger amount of data (references)

timber tide
#

oh no mmo

burnt vapor
#

So yes, make a third table that stores the item mods

#

The whole point is avoiding repetitive data, even here

keen dew
#

What's your definition of "huge"? MySQL handles comfortably hundreds of millions of rows

topaz mortar
topaz mortar
burnt vapor
#

If you generally avoid a feature because you're afraid of the performance, then stop worrying and just add it. You can always improve it later

#

But if you start limiting yourself now with hacks to make it more performant, often you will have a harder time fixing it

timber tide
#

I feel like databases though are one of the harder things to improve upon once you've made them into a spiderweb

topaz mortar
#

Ah not trying to take shortcuts here, just wondering what the optimal design is

burnt vapor
#

Databases themselves even have a ton of optimizations and functionalities if you really care, but you most likely will scale your data in the future and you should make it as accessible as possible

#

So don't cut corners basically πŸ˜„

topaz mortar
#

I was thought database normalization in high school 20 years ago, but my brain can't handle it really
the link is much more clear though

timber tide
#

Was it the 3rd form that's ideal but it's unlikely to do so you settle for 2nd form? I forget

burnt vapor
#

For what it's worth, if you use EntityFramework you just shape your classes and this is how the database will look like

#

Then you don't even need to worry about it, because it will be done for you

topaz mortar
#

there were actually 5 forms when I first learned it

#

maybe 4

burnt vapor
#

Code first πŸ”› πŸ”

#

I believe there are four

#

But I honestly forgot about the definitions until your question

#

Mostly it just comes with experience

topaz mortar
#

is EntityFramework something I should use? don't even know what it is, I saw it once before here and quickly looked at it, but it seems pretty complex

burnt vapor
#

In short it's a way to shape your database using a code first approach, where your tables are defined by the c# classes that implement the data

#

Then, using Linq, you write your queries

queen adder
#

Can we grab all asset, dirty them, then SaveAssets just for fun?

burnt vapor
#

More complex operations can just be called using regular SQL queries but EF saves the hassle of shaping your database

#

Not to mention it has a build in system for migrations so it can define updates to your database to update to or rollback from

acoustic berry
#

So a game object has 2 child objects that its script will need references to, in order to call getters and setter functions. This gameobject is the only thing in the game thats responsible for the 2 child objects, nothing else needs to mess with them. Normal coding convention would tell me to make them private references...

#

I could make them a public reference and just drag and drop in the slider

#

Is it normal in Unity to have some references be public when other coding standards would have them as private?

gaunt ice
#

serializefield private

wary sigil
#

if two scenes are loaded is it possible to reference an object in one scene in the other

wary sigil
#

how would i do that

#

becaus drag and dropping into public variables does not work

rare basin
#

singleton

#

or any other way from many possible

gaunt ice
#

all previous objects are destroyed unless they are in ddol scene or the scene is loaded as additive

#

Oh mb

hexed terrace
crisp jetty
#

do you guys know anything about broken audio issues? for some reason, the sound of the character attacking gets insanely broken and loud. It even overrides other audios that happened to overlap it

#

WARNING LOUD VOLUME

#

it only happened at the enemy attack sound, all the other sound is fine, so i figured it had something to do with the code?

nimble scaffold
#
using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour
{
    public float maxHealth = 100f;
    private float currentHealth;

    
    public Text healthText;

    

    void Start()
    {
        currentHealth = maxHealth;
        if (healthText == null)
        {
            healthText = GameObject.Find("HealthText").GetComponent<Text>();
        }
        UpdateHealthText(); 
    }

    // Rest of your script...

    void ApplyDamage(float damage)
    {
        currentHealth -= damage;
        UpdateHealthText(); 
        Debug.Log("Health reduced by: " + damage + ". Current Health: " + currentHealth);
    }

    void UpdateHealthText()
    {
        healthText.text = "Health: " + currentHealth.ToString() + "/100"; 
    }
}

this is the script and in this script my player cant deal with take damage when player falls ........ pls help me modify this code

crisp jetty
#

I think it can be fixed with animation event

nimble scaffold
#

help me about this one anyne pls

rare basin
#

but where are you calling htis methods

#

to take damage

#

does it print to console the debug log?

nimble scaffold
#

that it takes damage and full health reduces

timber tide
#

The concept you're looking for is scrolling combat text. There's usually a few tutorials on that on youtube if you look about.

queen adder
#

I assume the New Text is the health display

#

and it's not updating, is the problem

rare basin
#

also don't use Text its obsolete

nimble scaffold
#

hey everyone up here i will again starting my fps game project as i cant deal with the new input system of unity!!

#

deleted πŸ™‚

#

@rare basin does the new input system effect the button system thingy??? for my case it did

rare basin
#

yes

nimble scaffold
#

Wish me good luck everyone especially @rare basin

#

now i made a blank 3d project rn.... so now will it use the general input system or new input system??

rare basin
#

wdym general input system

#

there is no such thing

#

it's either the old input system (which is not recommended) and the new one

wintry quarry
#

You can just change the input system

nimble scaffold
wintry quarry
rare basin
nimble scaffold
#

how can i??

sonic remnant
#

noel

wintry quarry
#

The only other things would be:

  • changing all your code
  • removing the input system input module from EventSystem objects and adding the StandaloneInputModule
sonic remnant
wintry quarry
timber tide
sonic remnant
#

how can i do that? @timber tide sorry for asking noobish questions.

timber tide
#

Same as raycasting but instead you do it in an area

#

I've seen it done with unity collider events though, but it does seem like one of those things you need to juggle flags around.

sonic remnant
#

do i need a whole new script or jsut add id to my constructable script?\

timber tide
#

oh wait you do check with overlap here, but why are you using the collider events too?

#

pick one or the other, you don't want to use both

timber tide
atomic bison
#

good morning, i have a question about a performance, everytime i launch my game i make a connection to my db and get a list with 10k entrys.... yes is weird, but i need it, the question is, it takes 2-3 seconds, but in order to improve this or get better performance, instead of populate a List everytime i launch my app, can i make an addressable to order entry and check content etc...?

wintry quarry
#

If the request itself takes 3 seconds there's little you can do.

If it's your code afterwards taking that time, it can be optimized

#

If it's the request you could look into pagination or streaming

#

Though I kinda doubt you actually need to get 10k rows in one request...

ivory bobcat
quiet dune
#

Good day, if I have a Script referencing a GameObject I know has a specific Script attatched to it, is there any more performant way to access the Scripts methods than using GetComponent on the GameObject?

rich adder
#

[SerializedField] private MyScript myScript

quiet dune
#

But using a LayerMask, I know what I'm getting

rich adder
sullen rock
#

https://gdl.space/zafopomogi.cpp

Severity Code Description Project File Line Suppression State
Error CS0019 Operator '!=' cannot be applied to operands of type 'Fish' and 'Fish'

Im sorry what?

modest dust
#

Either way, just define a != operator for your Fish type and you're good

burnt vapor
#

I would advice you instead compare an inner property

sullen rock
modest dust
#

Then define a != operator

sullen rock
#

How would I do that?

burnt vapor
#

You can't compare two structs like that

#

Why would that work?

rich adder
#

or just make it a class..

burnt vapor
#

This only works with classes

#

Because you compare a reference

#

Structs do not have a reference

#

I would advice you instead compare an inner property

rich adder
#

thats why Unity has custom == for Vector3.

#

etc

sullen rock
#

I'm not exactly sure what you meant by the reference, I'll read up on that, I thought the difference is basically just struct not having methods

rich adder
#

structs can most def have methods lol

burnt vapor
#

If you don't know what a reference is I HIGHLY suggest you stop using structs

#

Just use classes

rich adder
#

completely different ballgame how they get stored

#

major reason structs can never be null but class can

burnt vapor
#

The major difference is that classes are allocated on the heap and prone to garbage collection. Long story short this reduces performance compared to structs. It's a complex topic.

#

In laymans terms, if you pass a struct you create a copy and this means that any changes are only persisting in that copy and not the original, unlike classes which you pass around by reference and remains the same. This can cause major issues for obvious reasons, but the benefit is no allocation.

sullen rock
#

Feels like in this case the class will probably be the better solution, since I'm moving the data around quite a bit

#

Well, thanks for the explanation, I'll swap to a class and compare a unique property

rich adder
sullen rock
#

I know, but I'm not sure if that's the better than comparing a unique property of the class

kind dirge
#

public void startpairing()
{
if (PhotonNetwork.IsConnected && PhotonNetwork.IsMasterClient)
{
// Fetch all the players in the room
Player[] photonPlayers = PhotonNetwork.PlayerList;
List<Player> players = new List<Player>(photonPlayers);

        // Check if we have enough players for pairing
        if (players.Count >= 2 && players.Count % 2 == 0)
        {
            // Form pairs
            while (players.Count > 0)
            {
                Player player1 = players[0];
                Player player2 = players[1];

                    RoomOptions subroomOptions = new RoomOptions { IsVisible = false, MaxPlayers = 2 };
                    PhotonNetwork.JoinOrCreateRoom("abcd", subroomOptions, TypedLobby.Default);
                 PhotonNetwork.SetPlayerCustomProperties(new ExitGames.Client.Photon.Hashtable { { "Subroom", "abcd" } });
                players.RemoveAt(0);
                players.RemoveAt(0);
            }
        }
    }
}

here is the code , where i paired players , and then i want to send them in separate sub room, but the problem is , subroom is not creating and giving error of

CreateRoom failed. Client is on GameServer (must be Master Server for matchmaking) and ready. Wait for callback: OnJoinedLobby or OnConnectedToMaster.

can anyone help me in this problem
Thanks

sonic remnant
timber tide
#

Ignore the bools and just compare everything each update

#

oh wait sorry let me refine this

sonic remnant
#

no problem im glad that you are helping me

#

and i dont want to use IsBuilding, i want to use isValidToBeBuild, Because then i can build (build logic is in the construction manager)

#

is that okay?

#

HandleConstructionModeLogic() from the buildingmanager

#

maybe i need to change isValidToBeBuild to public bool isValidPlacement; in the construtable script?

timber tide
#
void Update()
{
    if(IsBuilding && CheckForOverlap())
    {
        //There is no overlap and there is ground so it's valid to build
    }
}

bool CheckOverlap()
{
    Collider[] colliders = Physics.OverlapBox(solidCollider.bounds.center, solidCollider.bounds.extents, transform.rotation, LayerMask.GetMask("Default"));

    isGrounded = false;

    foreach (Collider col in colliders)
    {
        if (col.CompareTag("Tree") || col.CompareTag("pickable"))
        {
            return false;
        }

        else if (col.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

    return isGrounded;
}```
Do actually need a bool here if you're doing it by tags.
#

I'd suggest just use layer masks

#

but it should be doable as is

sonic remnant
#

do i need to change the IsBuilding to isValidPlacement?

timber tide
#

Problem with doing grounded here is I'd expect you to be able to build into the terrain, so you need additional logic for that. I wouldn't suggest it colliding with terrain to be valid. More that you want to know it's above the terrain enough to build.

#

Better yet just raycast from a point in front of your player downward and calculate that.

sonic remnant
#

but i have different objects to use in my constructionholder

sonic remnant
#

but like i said. it has to work with the constructionmanager script aswell. that has the build activation.
https://gdl.space/gemufeqebu.cs

i would love to implement the raycasting function. πŸ™‚ @timber tide

timber tide
#

If you've got a specific problem do post, but with what you got there I assume you've got a good idea.

frozen mantle
stark flint
#

Hello so I recently started Unity and have installed the c#, c# dev kit, and unity extension and selected vscode as the ide im using and I have installed .net however my code is not coloured in and will not recomend code to me related to c# it just brings random stuff up

rich adder
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

stark flint
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

scenic cipher
stark flint
#

Well I have been using VSC since I started programming and VS has a worse layout

#

btw I had already done all those things navarone

rich adder
stark flint
rich adder
#

screenshot console window in unity as well

stark flint
#

it is a new console nothing is in it yet

rich adder
#

alr did you try hitting Regen Project Files inside External tools ?

stark flint
rich adder
#

yup

stark flint
#

nothing changed

rich adder
#

open the script from unity, do you see anything in Output in VSC?

stark flint
summer stump
stark flint
#

yea

rich adder
#

weird says loaded

#

try opening up the .sln

stark flint
#

what is that

rich adder
#

its the solution file inside your project

stark flint
rich adder
#

alr

rich adder
stark flint
#

yea

rich adder
stark flint
#

i have

rich adder
#

clear output, do it again.
anything in output ?

stark flint
naive pumice
#

hey when i retrieve text from TextMeshProUGUI and print the output, it always shows a ??? at the end of the string written in the text field, is that normal ?

naive pumice
#

yes sure just a sec

rich adder
# stark flint

I recommend you just start using VS visualstudio until you get that sorted somehow. Try combinations of restarting and, solution/cspro files then regen project files and open script from unity again.
it says it loaded...vscode bs as usual

keen dew
#

I can already tell that if it's an input field then the type is wrong

stark flint
#

but it happens on vs aswell

naive pumice
#
[SerializeField]
private TextMeshProUGUI emailInputTxtSignUp;

private void SignUp()
    {
        string finalEmail = emailInputTxtSignUp.text.Trim().Replace("???", "");

        if (finalEmail != "")
        {
            Debug.Log("Email sign up: " + finalEmail); 
        }
    }

And the debug log prints :

2023/11/30 16:56:11.088 3556 3682 Info Unity Email sign up: test@gmail.com???
#

If i remove the Trim and Replace it also shows it, so i guess it may com from the Debug ?

keen dew
rich adder
naive pumice
#

well i will check what it is haha i have started with unity few days ago

polar acorn
#

There's a very strange error with those that I found a few weeks ago and submitted a big report, lemme go find the Unicode character you have to replace for those

polar acorn
#

.Replace("\u200B", "")

#

Use that instead of (or in addition to) trim

keen dew
#

TMP_InputField already excludes that character

naive pumice
#

oh thanks will try this

keen dew
#

The more general type picks up the entire element which includes a control character which is possibly the caret position

polar acorn
naive pumice
#

The TextComponent is the component i take the text from

#

thanks it works perfectly @polar acorn

sonic remnant
#

im one step further! the Tree detection works and i can now build with the raycast finally! only problem im facing right now is that i can build through a tree with my ghost object. here are the scripts and video. thank you community ❀️

constructable:
https://gdl.space/igapuyaqaq.cs
constructionmanager:
https://gdl.space/itabopeboy.cs
ghostitem:
https://gdl.space/popokefade.cpp

delicate portal
#

How do I shoot 3 raycasts from a trasform? It's center, its feet level, and its head level?

#

I have scriptableObjects setup for this case, so I cant create just 2 transforms named feet, and head

#

Should be more complicated

rare basin
#

Why you can't, how are you going to determine the raycasts origin then

verbal dome
#

Not sure why you need a SO for that

rare basin
#

You can have SO for Raycast data's like range, layermask etc

delicate portal
rare basin
#

But why would you do Raycast in there

#

Make a mono behaviour like building detector

#

Don't do it in the so

verbal dome
#

Would be cleaner to do the raycast in a monobehaviour

#

And use settings from the SO

verbal dome
rare basin
#

That's not rly a good approach

delicate portal
#

I'm not using the SO

rare basin
#

Better to use the transforms so you can rotate them and position easily

#

And just do forward as the direction

verbal dome
#

I dont like polluting my scene with extra gameobjects so I use simple data for stuff like this

#

But transforms are easier, yes. Banan said they cant use transforms though - why is that? Isnt there a prefab involved that you can add the transforms to?

#

@delicate portal

rare basin
#

I don't see how is using scriptable objects blocking him to make 3 transform as he said

delicate portal
#

I have a building ghost with a meshrenderer, and each time I click on a button, with(for example) a bed icon on it, it switches the mesh to the bed. I want the 3 raycasts position to change dinamically depenmding where is the center, feet, and the head. If select a table, thats another mesh.

#

I hope its clear

verbal dome
#

Then raycast from each of those. Can put them in a list/array and do it in a loop too

fierce mortar
#

I want to make a top down shooter, should i put the shooting script in the same script with the movement script because of things like recoil

verbal dome
desert elm
#

is there a way to compare all the entries in a list and pick the highest/lowest one?

desert elm
#

thanks

queen adder
#

I could have a seperate parent on the physics object with a different rotation to the actual object, but it seems like a very roundabout way of fixing something that could probably be done in 2 lines of code

rich adder
queen adder
#

I still want it to rotate with the camera

rich adder
#

cant you just parent it to player /cam then?

queen adder
#

parenting is very wonky with physics

#

causes it to ghost through walls and the likes

rich adder
#

true. you can try using just velocity to move it from prev pos - new pos

queen adder
#

I just need to try and sort of snapshot the start point, and set that to the rotation

#

But a parent - child with seperate rotations might actually be the best way

ruby python
#

Can you not just disable physics on the object when you pick it up and re-enable when you drop it?

rich adder
#

its ugly because it goes through walls

ruby python
#

Ah fair point.

#

Or lock the constraints?

queen adder
#

I still want it to move relative to the camera, just not reset the rotation once picked up

rich adder
desert elm
ruby python
#

Might be wrong, but record the rotation, parent to player, set the rotation to the recorded rotation?

queen adder
#

Holdarea rotation is just a get of a transform attached to where my characters holds stuff

desert elm
#

Is it possible to set a gameobject as a variable?

rich adder
#

ya lol

rich adder
#

not very useful but sure

novel shoal
#

rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.up*1000);
Debug.Log("force added");
the Debug.log line works, but it doesn't add any force
the object has a rigidbody

queen adder
#

Yes it worked

desert elm
ruby python
#

Yaaay, I helped. lol.

rare basin
#

if the debug log works, it adds the force

#

if the rb is referenced

rich adder
#

it don't matter they both work fine , if they do have scripts on them though mind as well reference that

ruby python
#

@novel shoal Try increasing/decreasing the mass on the rigidbody.

novel shoal
ruby python
#

And the drag maybe

novel shoal
#

same result

queen adder
#

(For anyone Searching for a similar issue in the Search bar this was the resolution)
Added a gameObject as a sibling to the hold area.
Once object is being picked up, set the new object to the rotation of the hold area then parent it to the hold are.
Then replace the moveRotation hold area to the new object's rotation.
Then just unparent it once you're dropping the object

summer stump
novel shoal
#

now it works, and i have no idea why, i literally changed nothing

rich adder
#

@queen adder thats kinda doing what i said no? with an extra step?

queen adder
#

Yeah what you said worked

rich adder
#

oh ok lol

novel shoal
#

navarone new pfp lol

desert elm
queen adder
#

I'm just detailing it for A) myself when I inevitably run into this again and B) anyone who's searching for help in my shoes

rich adder
#

every MonoBehaviour has access to their .gameObject and .transform respectively

wintry quarry
desert elm
#

how do you use the transform directly?

wintry quarry
#

Transform

#

make a variable of that type

#

like you would any other variable

rich adder
desert elm
wintry quarry
#

This is Unity 101.

public Transform theObjectIWant;```
Then drag and drop in the inspector to assign it
#

"transform value" is a weird phrase too

#

Transform is a component. That component has things like position and rotation

timber tide
#

time for unity courses

desert elm
#

I already did those

wintry quarry
#

go again

#

Basic variable assignment and referencing is like the most important thing

summer stump
#

I'm confused how making a reference to a Transform would NOT help you access that objects transform..

summer stump
desert elm
#

yeah wait a moment talking with someone I can actually understand

wintry quarry
#

(it's probably ChatGPT)

desert elm
wintry quarry
#

Ah there's a language barrier

desert elm
#

Yeah- and yeah it was simple just had no idea what you were saying because I cannot understand english well at midnight, sorry

rare basin
#

its 8PM in slovakia

#

wdym midnight

summer stump
rare basin
#

no

frosty hound
#

Discord user discovers there are, in fact, people living in multiple timezones. 🀯

rare basin
#

cringe

polar acorn
#

Breaking news: People can sometimes live outside of the place they are from

rare basin
#

breaking news discord users are mostly cringy af

summer stump
desert elm
novel shoal
polar acorn
rare basin
short hazel
#

Telling people they are cringe while looking up the time to see if they were lying or not. Ironic

rare basin
#

i didin't look anything but k πŸ˜„

summer stump
forest karma
#

When pressing play, my enemy navmesh agent's patrol point seems to moving extremely far away. how can i fix this?
here is the code
https://hastebin.com/share/ogitesimel.csharp

desert elm
#

the biggest problem for me was that this bit wasn't showing up in the inspector because I had yet to update the script
man sometimes I am stupid

polar acorn
forest karma
#

The 2nd bit

polar acorn
# forest karma The 2nd bit

I would suggest logging the target position every time you set it. See which function is called the most recent, it could be that your chase or attack states are overwriting your patrol point destination

stark flint
#

Hello I am writing some code to allow the user to move and test interaction however my character is not moving https://pastebin.com/2APzENgB

vague furnace
#

how can i make it so random range doesnt generate same values

prime lodge
#

Why it doesnt work
U is float btw

languid spire
#

because 0.001 is a double

prime lodge
#

iam stupid sorry

languid spire
vague furnace
languid spire
#

what about it do you not understand?

novel shoal
#

transform.Translate(Vector3.leftTime.deltaTimespeed);
this doesn't move an object wtf

vague furnace
#

how do i do list

novel shoal
#

(the speed is a public float 30f)

languid spire
novel shoal
languid spire
#

no that is an array not a List

novel shoal
#

oh lol

desert elm
#

is it possible to use Contains
but the inverse i.e check if it doesn't contain x?

languid spire
#

Contains returns a bool so, yes

desert elm
#

oh thanks didnt know that

eternal falconBOT
austere monolith
#

https://hastebin.com/share/olaxunabut.csharp https://hastebin.com/share/licudumedo.csharp when i try attaching the exact same scripts for another gun, the game glitches, for example when i drop the already equipped weapon, it just freezes randomly in the air, and when i pick up the other one it starts following my camera in a weird orientation, plus even when i dont have it equipped, it follows my camera

normal slate
#

Hey I am working on this project right now and I need to figure out a way to equip and unequip this weapon does anyone know how to store the position and rotation based on the parent obect in this situation:

#

So the gun is what I want to equip and unequip

wintry quarry
normal slate
#

oh

#

uh just a second

#

i cant find it give me a few

#

do i need to run a command to grab that?

austere monolith
#

k ill find it out

normal slate
#

OH I SEE

#

so its like saved on the child so if i store those values ahhh i see thanks it auto does it for me so i just copy paste the positions and rotations from the transform sweet thats so nice

normal slate
#

is that a joke XD

rocky canyon
#

nah

normal slate
#

oh thanks haha

rocky canyon
#

but i do question whether it'd be better to just have a bigger circle overlap the player and some of their hands

normal slate
#

i see what you mean but for accuracy sake this seems to work best for me right now

rocky canyon
normal slate
#

let me show you what I mean

rocky canyon
#

b/c it seems like you'd have a good Snag point

#

for something like this

normal slate
#

Oh i see what you mean now

rocky canyon
#

like the two colliders could get hung up b/c they stick out past the player

#

but yea.. just an thought i wanted to share with ya

normal slate
#

yeah ill do that thanks

rocky canyon
#

do w/e working πŸ‘

#

cool little character tho πŸ˜„

normal slate
#

thanks haha

#

like this?

#

i kinda am thinking I remove the gun colider all together maybe

rocky canyon
#

reminds me of these guys πŸ˜„

#

sometimes came with a school bus that looked like an egg carton πŸ˜„

rocky canyon
# normal slate like this?

seems okay.. it being offcenter may matter if u were using physics and stuff.. maybe more centered if that becomes a problem..

#

if its not a problem looks good to me πŸ‘

normal slate
rocky canyon
#

perfect!

normal slate
#

how big of an impact does it have because

#

I can also do this

rocky canyon
#

having multiple colliders isnt really a problem performance wise.. i was just worried about it getting snagged when rotating

#

using a single collder like that would prevent that

normal slate
#

oh yeah I get what you mean

#

like the gun would have an issue you would force some sort of movement on the player while rotating yeah

#

makes sense thanks πŸ™‚

rocky canyon
#

mmhm

unborn sinew
#
    private void Update()
    {
        torque = input.Player.Turn.ReadValue<float>() * 0.1f;
        thrust = input.Player.Thrust.ReadValue<float>();
        isDamping = input.Player.Damp.ReadValue<float>() != 0f;
    }

    private void FixedUpdate()
    {
        if (isDamping)
        {
            rb.velocity *= dampStrength;
            rb.angularVelocity *= dampStrength;
        }

        if (torque != 0f)
        {
            rb.AddTorque(torque);
        }

        if (thrust != 0f)
        {
            rb.AddRelativeForce(transform.up * thrust * propulsionForce);
        }
    }

When I play (gravity set to zero btw), and do some rotation, the thrust direction changes to a direction which is not forward. It is kinda forward, but angled slightly. What's the possible cause?

forest karma
#

I keep having an error saying ""SetDestination" can only be called on an active agent that has been placed on a NavMesh."
Even though I have assigned the robot onto the baked navmesh, How can I fix this error?

rocky canyon
#

normally happens when the navmesh agent is too far from the ground

forest karma
#

Let me show u the navmesh bake

short hazel
#

Your enemies are under a parent object, that might be the cause?

wintry quarry
forest karma
#

Ah ur right

#

It's under an empty gameovject

wintry quarry
forest karma
#

Oh yeah. How do I fix the robot floating. I'm using transform.LookAt.

wintry quarry
forest karma
#

Wait no the error still shows

wintry quarry
scenic cipher
forest karma
#

Wdym

rocky canyon
#

u should probably only be rotating the graphics of the navmeshagent.. and keepin the main agent straight up and down.. rotation could be kicking the feet up off the ground

forest karma
forest karma
#

That orange lines is the navmesh bake

rocky canyon
#

looks like its up above the ground plane to me

short hazel
#

The nav mesh is under the enemy? wat

#

Ah no it's under that empty parent

forest karma
#

No I moved it

scenic cipher
forest karma
#

And it's still got error

rocky canyon
#

a properly baked mesh should appear blue when in the navigation panel

scenic cipher
#

@forest karma Just to confirm, the Robot is type Humanoid?

forest karma
#

Yea

#

In the navmesh agent component

scenic cipher
#

Click "Bake" again, it doesn't look like it is baked

#

@forest karma What is the layer on your ground?

rocky canyon
#

i need to fiddle with the new versions of unity..

#

im out of hte loop on navmesh's and their new functionallity

forest karma
#

whatIsGround

#

That's my layer on the ground

rocky canyon
#

!sky

#

i use static tickbox for my navmesh but like i said.. not used the newer versions.. but that was always an ez way for me get one up and workin

scenic cipher
#

@forest karma Hmm, what if you tried setting it to include all layers in the NavMeshSurface?

scenic cipher
rocky canyon
#

nice..

#

what version of unity do u use elctro?

scenic cipher
#

2022.x

forest karma
#

That just breaks it

scenic cipher
rocky canyon
forest karma
#

My enemy goes really far away

#

Constantly

scenic cipher
#

Is it giving you that error you had before?

forest karma
#

Yes

scenic cipher
#

How is the enemy moving if its unable to find the navmesh πŸ€”

forest karma
#

It doesn't move anymore when I sid everything for layers

scenic cipher
#

Was it moving before?

forest karma
#

That was just me accidently using Nothing as layer

#

Even on nothing

#

It still gives error and doesn't move

#

Wtf

#

Should I show you my script/components

scenic cipher
#

Can you select NavMeshBake object and send another picture please

#

Also, are you using the new or old AI system?

forest karma
#

Dont know, just followed tutorial

#

Here is the enemy components

scenic cipher
#

It seems like an issue with the NavMeshSurface since it should be showing blue on the ground

forest karma
#

Yes

#

Ur right

#

Should the navmesh not be a child of the enemy?

#

instead a parent?

scenic cipher
#

You could try, but it shouldn't matter

slender nymph
scenic cipher
#

Can you open the Package Manager and search "ai" and tell me the version you're using? I'm not familiar with the old version

forest karma
scenic cipher
#

Change it to "In Project" or "Unity Registry" and search again

forest karma
#

Nothing showing lol

#

Wait I imported the navmesh file by dragging it into my project

slender nymph
#

yeah they are using the 1.0 version before it was a package that needed to be installed separately

forest karma
#

From github

scenic cipher
#

Is AI Navigation 2.0 available on Unity 2021?

elder atlas
#

I believe so

#

actually im mistaken

scenic cipher
#

@forest karma Can you try setting the ground to Static? Like I said earlier I'm not familiar with the old AI Navigation but I know Static must be ticked for something.

#

You should also consider upgrading to Unity 2022

elder atlas
#

the old navigation is weird I had so many issues getting it to work properly

forest karma
#

Guys I think it's just something small so

#

Coz even thr bake should be blue

scenic cipher
#

You should still use the updated AI Navigation 😬

#

Is Static ticked on for the ground game object?

forest karma
#

Yep

#

Do u want to se ecode

scenic cipher
#

It doesn't seem to be an issue with the code unless the code is moving the enemy off of the navmesh

#

@forest karma When you select the NavMeshSurface object there is a white box, can you confirm the ground is inside of it?

forest karma
#

its an orange box

#

looks like its in for me

scenic cipher
#

Actually it may be orange

#

@forest karma I'm really not sure what is causing that error, everything looks correct.

hidden sun
#

hi, any idea why my obj is disappearing? when i press click

#

nvm, i forgot to set z to 0

rocky canyon
#

in playmode select the object in the hierarchy and press F it will focus on it and show u where it is

scenic cipher
hidden sun
rocky canyon
#

u can debug the transform position and figure out where its going and why

hidden sun
#

z was -10

#

ty anyway

rocky canyon
#

np good stuff

forest karma
#

How can I make my robot have the correct y position when looking at my player to shoot

rocky canyon
#

use the player's Y position to look at

forest karma
#
private void AttackPlayer()
    {
        enemyAI.SetDestination(transform.position);//Enemy will stop moving when attacking
        transform.LookAt(player);//Enemy will look at the player when attacking
scenic cipher
rocky canyon
#

i used projectile bullets.. so i would spawn the bullet.. rotate it towards the player and then fire it forward πŸ˜„

#

then the actually enemies direction doesnt matter as much.. just gotta get it ballpark lol

forest karma
scenic cipher
# forest karma how

Try this,

transform.LookAt(new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z));```
rocky canyon
#

u can manually change individual properties..

#

like transform.position.x = floatValue; for example

forest karma
#

Doesnt work lol, bro thinks he is a penguin

scenic cipher
#

Try this.

        transform.LookAt(new Vector3(transform.position.x, player.transform.position.y, transform.position.z));```
rocky canyon
#

^ my favorite little hack

forest karma
#

Yes he is in the right direction now

#

But why is he in the ground??

rocky canyon
#

although i do it reverse.. i use the transforms, y position so it always looks forward.. that way if the player is above or below him he dont do no crazy rotations lol

#

ur graphics are probably mis-aligned

#

just take the graphics and move them upwards?

forest karma
#

Yeah, but i dont like the new line of code since it ruins my projectile shooting now

scenic cipher
rocky canyon
#

pivot points and stuff

#

i think its probably how u have the enemy constructed..

#

the parents forward probably isnt eh same as the enemy model's forward

forest karma
#

Thats the whole code if u wantd to see it

rocky canyon
#

so when the parent looks forward.. the enemy gets rotated facing downards

scenic cipher
#

@forest karma Check the NavMeshAgent collision, you may need to change the offset or scale

frozen mantle
plain elbow
#

how much coding experience do you need to start using unity? im new to game development and don’t really have coding experience other than HTML and some python.

rocky canyon
#

everyone starts with zero unity experience..

#

if u have code experience at all u got a headstart

timber tide
#

sounds like you have more experience than those with no coding knowledge so you're ahead of the curve

scenic cipher
forest karma
#

Im not sure how to fix it in blender though

scenic cipher
rocky canyon
plain elbow
forest karma
#

it is parented

rocky canyon
#

since its a whole system that you have already

timber tide
#

starting unity without knowledge of constructors and objects is asking to fail

rocky canyon
#

you learn thru failures tho

frozen mantle
timber tide
#

imagine trying a new language out and you're wondering how to instantiate objects

frozen mantle
#

Carby = level up

rocky canyon
scenic cipher
frozen mantle
#

fair enough, i'll post there

#

should i delete my post here? i don't wanna get done in for cross posting

rocky canyon
#

i had a friend make a system like that.. took him weeks to trouble shoot all the little problems here and there

#

def a process

scenic cipher
rocky canyon
#

i mean..

#

shouldn't be too hard imo

#

the terminology would be trickier.. but u learn that as u expose urself to the mechanics

frozen mantle
#

yeah i think understanding objects and instantiation is pretty easy, it's just that beginners get jumbled up by terms

rocky canyon
#

start with tutorials.. unity learn perhaps.. get ur bearings around the engine.. make a simple as possible game from following others..
(now you have a grasp on whats going on).. adapt what you've learned to make exactly what you want. research the things specifically that you get hung up on..

#

rinse and repeat.. and you're golden

slender nymph
shell zephyr
#

Thanks!

tender stag
#

if i have scriptable objects called ItemData

#

how do i find all of them here

#

is it even possible?

#

theres no scriptable objects

feral mirage
scenic cipher
#

@tender stag A ScriptableObject is a Script. It would be under Script

tender stag
#

i need like these

#

not the actual scripts

#

yeah i dont think its possible

#

nevermind

slender nymph
#

if you want to find instances of that kind of object, then search t:ItemData

tender stag
#

oh yeah

#

alright thanks man

lone sable
#

Any idea why when using IDeselectHandler (And Select) and IPointerDownHandler(And Up) that when OnPointerDown is called, and I move the mouse (Still within the bounding box) that OnDeselect gets called?

timber tide
#

Perhaps events are being consumed

#

or maybe can see if current gameobject that's selected isn't changing if you're using other events

lone sable
#

Hmm. I shall dig into it more.

I was sort of hoping somoene was going to say "Yeah thats just unity being unity."

feral mirage
#

There are always things to do which can circumvent stuff. It's all about figuring it out.

timber tide
#

I do dislike these interfaces but I cant be bothered implementing them myself. Especially the drag interfaces.

lone sable
#

Dug into it more, its actually OnPointerUp thats being called for some reason...

willow pike
#

Hello, im developing a procΓ©durale video game map and I have a problem with shaders. (I’m new on unity) . I made perlin’s Algorithm and due to the height of my map, I want to applicate a specific shader. (Water, sand, grass…) but, a mesh can only have a single shader. So what am I supposed to do if I want to applicate different shaders to my different height of my map. For now, I just applicate a color to my different height. Thank you for answer ! πŸ™‚

timber tide
#

They're just textures, why do you need multiple shaders?

willow pike
#

Well I have a good grass shader I design, same for water and I can’t applied both to a single mesh.

teal viper
#

Water and grass should probably be a separate object/mesh.

willow pike
#

I don’t understand, because my noise is generate with some different height. And I say in unity if height > 0.1 then put color blue. And it looks like a nice start of Γ  Map. But grass water sand etc are in the same shader and is a unique material. So I’m a bit stuck

lone sable
#

So, it was indeed, a "Unity being Unity" problem.

willow pike
timber tide
#

what makes this a shader and not a surface texture / vertex coloring

teal viper
#

Usually procedural generation involves more than generating one mesh. You'd usually have a virtual representation of you world in the form of chunks/cells grid. You would then use different systems to generate terrain, water, grass and what not.@willow pike

willow pike
#

My shader is in a material but I want to apply it on my mesh but I just found that in mesh renderer I can apply multiple materials

teal viper
#

You can do that with submeshes yeah. But that isn't really different from generating several separate meshes.

round scaffold
#

I want to make an item drag and drop system, but for some reason the drag interfaces wont event register my clicks at all am i missing somethin stupid again

slender nymph
#

is this component attached to a UI object or a world space object?

slender nymph
#

and you have an event system in the scene?

round scaffold
#

yes

slender nymph
#

then look at the event system's preview window and see if it is detecting your object or if something else is possibly blocking the raycast from the mouse

round scaffold
#

deactivated every other ui canvas and made sure anything else was either off or out of the way still doesnt register my clicks

slender nymph
#

and have you checked the preview window of the EventSystem to see if it is detecting anything?

round scaffold
#

i dont think its detecting anything

#

its detecting an interaction prompt ui i have but not the book?

slender nymph
#

does your canvas have a GraphicsRaycaster?

round scaffold
#

yea

slender nymph
#

then show the event system's preview window while you try to select that object at runtime

compact dirge
#

no way for detect if a gameobject is colliding something in this exact moment (not with onCollisionEnter/Exit) other then rayCast?

slender nymph
#

well i can't tell what's wrong with it. but i can tell it isn't a code issue πŸ€·β€β™‚οΈ
ask in #πŸ“²β”ƒui-ux and provide all of the relevant details for your UI setup

slender nymph
scenic cipher
compact dirge
#

I guess that the raycast is the most light function, right?

scenic cipher
#

Yes, raycast is most likely most performant.

round sentinel
scenic cipher
round sentinel
#

yes

#

here ?

scenic cipher
#

Yes

round sentinel
#

oh

#

its 2000 messages long it doesnt let me

scenic cipher
#

I just need your movement code

round sentinel
#

CharacterController characterController;
void Start()
{
characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}

void Update()
{

    #region Handles Movment
    Vector3 forward = transform.TransformDirection(Vector3.forward);
    Vector3 right = transform.TransformDirection(Vector3.right);

    // Press Left Shift to run
    bool isRunning = Input.GetKey(KeyCode.LeftShift);
    float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
    float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
    float movementDirectionY = moveDirection.y;
    moveDirection = (forward * curSpeedX) + (right * curSpeedY);

    #endregion

    #region Handles Jumping
    if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
    {
        moveDirection.y = jumpPower;
    }
    else
    {
        moveDirection.y = movementDirectionY;
    }

    if (!characterController.isGrounded)
    {
        moveDirection.y -= gravity * Time.deltaTime;
    }

    #endregion

    #region Handles Rotation
    characterController.Move(moveDirection * Time.deltaTime);

    if (canMove)
    {
        rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
        rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
        transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
    }

    #endregion
}

}

scenic cipher
#

For future reference, please put your code into a codeblock mark down like this,

    void Start()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {

        #region Handles Movment
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 right = transform.TransformDirection(Vector3.right);

        // Press Left Shift to run
        bool isRunning = Input.GetKey(KeyCode.LeftShift);
        float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
        float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
        float movementDirectionY = moveDirection.y;
        moveDirection = (forward * curSpeedX) + (right * curSpeedY);

        #endregion

        #region Handles Jumping
        if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
        {
            moveDirection.y = jumpPower;
        }
        else
        {
            moveDirection.y = movementDirectionY;
        }

        if (!characterController.isGrounded)
        {
            moveDirection.y -= gravity * Time.deltaTime;
        }

        #endregion

        #region Handles Rotation
        characterController.Move(moveDirection * Time.deltaTime);

        if (canMove)
        {
            rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
            transform.rotation = Quaternion.Euler(0, Input.GetAxis("Mouse X") lookSpeed, 0);
        }

        #endregion
    }
}```
#

Let me take a look at your code

round sentinel
#

ahh my bad

scenic cipher
#

Try this.

    void Update()
    {

        #region Handles Movment

        // Press Left Shift to run
        bool isRunning = Input.GetKey(KeyCode.LeftShift);
        float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
        float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
        float movementDirectionY = moveDirection.y;
        moveDirection = (transform.forward * curSpeedX) + (transform.right * curSpeedY);

        #endregion

        #region Handles Jumping
        if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
            moveDirection.y = jumpPower;
        else
            moveDirection.y = movementDirectionY;

        if (!characterController.isGrounded)
            moveDirection.y -= gravity * Time.deltaTime;

        #endregion

        #region Handles Rotation
        characterController.Move(moveDirection * Time.deltaTime);

        if (canMove)
        {
            rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
            transform.rotation = Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
        }

        #endregion
    }```
round sentinel
scenic cipher
#

Which line is line 66?

round sentinel
scenic cipher
#

You were missing a comma, I added the comma in the code above

round sentinel
#

oh wait i mean this

austere monolith
#

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

public class PlayerLook : MonoBehaviour
{
public float sensitivityX = 2f;
public float sensitivityY = 2f;

private float rotationX = 0f;


// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void Update()
{
    float mouseY = Input.GetAxis("Horizontal") * sensitivityX;
    float mouseX = Input.GetAxis("Vertical") * sensitivityY;

    transform.Rotate(Vector3.up * mouseX);

    rotationX -= mouseY;
    rotationX = Mathf.Clamp(rotationX, -90f, 90f);

    Camera.main.transform.localRotation = Quaternion.Euler(rotationX, 0f, 0f);
}

}

whats wrong with this code?

austere monolith
#

there is no error but i cant look around

scenic cipher
scenic cipher
# austere monolith using System.Collections; using System.Collections.Generic; using UnityEngine; ...

Try this.

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

public class PlayerLook : MonoBehaviour
{
    public float sensitivityX = 2f;
    public float sensitivityY = 2f;

    private float rotationX = 0f;
    private float rotationY = 0f;


    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseY = Input.GetAxis("Mouse Y") * sensitivityY;
        float mouseX = Input.GetAxis("Mouse X") * sensitivityX;

        transform.Rotate(Vector3.up * mouseX);

        rotationY += mouseX;
        rotationX -= mouseY;
        rotationX = Mathf.Clamp(rotationX, -90f, 90f);

        Camera.main.transform.localRotation = Quaternion.Euler(rotationX, rotationY, 0f);
    }
}
austere monolith
#

vertical works

#

horizontal nah

scenic cipher
#

You need to add a rotationY to the Quaternion.Euler()

austere monolith
#

would i make another private float

round sentinel
scenic cipher
scenic cipher
austere monolith
#

i kind of suck at this whole coding thing, i added a rotationY then put Quaternion.Euler(rotationX, rotationY, 0f);

scenic cipher
austere monolith
#

erm

#

i think y movement

scenic cipher
austere monolith
#

looking i mean

scenic cipher
#

This line does the rotating πŸ€”

Camera.main.transform.localRotation = Quaternion.Euler(rotationX, rotationY, 0f);```
austere monolith
#

no idea what this means

#

oh

scenic cipher
#

I made a mistake, I have updated the code.

austere monolith
scenic cipher
#

Just comment that line out, and test without it. I don't think its needed.

austere monolith
#

perfect it works! also i try it without that line

#

you are right πŸ˜…

#

ty

scenic cipher
#

You're welcome.

austere monolith
#

wait what

round sentinel
austere monolith
#

another error XD

scenic cipher
austere monolith
#

the issue i have is when i look in a direction i spawn in, i go forward, then i look to the left or any other direction, i click forward and i still go in the same direction always, basically when i turn it doesnt update that and it keeps the same directions

#

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

public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 3f;

private Rigidbody rb;


// Start is called before the first frame update
private void Start()
{
    rb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void FixedUpdate()
{
    float horizontalInput = Input.GetAxis("Horizontal");
    float verticalInput = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput);

    rb.velocity = movement * moveSpeed;


}

}

limpid forum
#

Use This to clean your code up

#

Three of these `

eternal falconBOT
austere monolith
#

hola como estas amigo

#

okay

scenic cipher
#

@austere monolith Try this

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

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 3f;

    private Rigidbody rb;


    // Start is called before the first frame update
    private void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector3 movement = transform.right * horizontalInput + transform.forward * verticalInput;

        rb.velocity = movement * moveSpeed;
    }
}```
austere monolith
#

what the

#

oh

#

ty again XD

scenic cipher
#

You're welcome.

austere monolith
#

aw it doesnt work

#

but it makes sense?

scenic cipher
#

Is there a reason you're using RIgidBody instead of CharacterController for movement?

austere monolith
#

the built in gravity

scenic cipher
#

You can still use a RigidBody with CharacterController movement.

#

I've always used CharacterController for movement, so I'm not sure what your issue is.

austere monolith
#

ill go learn how to do it in character controller

limpid forum
scenic cipher
#

Heres updated code if you want to use CharacterController. Make sure to add a Character Controller component to your game object.

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

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 3f;

    private Rigidbody rb;
    private CharacterController characterController;


    // Start is called before the first frame update
    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        characterController = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector3 movement = transform.right * horizontalInput + transform.forward * verticalInput;

        characterController.Move(movement * moveSpeed * Time.deltaTime);
    }
}```
austere monolith
#

why does it say object reference not set to instance of object on the player, i click on the player and theres nothing to assign?

scenic cipher
#

Did you add a Character Controller component to your game object?

austere monolith
#

yes

scenic cipher
#

Send me the error please.

austere monolith
amber spruce
#

anyone know why my player is just falling through the map

scenic cipher
amber spruce
#

yeah

austere monolith
scenic cipher
#

@amber spruce What are the Layers on both the players and ground?

austere monolith
amber spruce
#

i found the issue

scenic cipher
amber spruce
austere monolith
#

aight

scenic cipher
# austere monolith

Can you try copying the code I sent above. You may have copied it before I edited it.

austere monolith
#

oh you updated it

#

k theres no errors but the issue of direction still isnt fixed

#

chatgpt says

using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 3f;

    private Rigidbody rb;
    private Transform cameraTransform; // Reference to the camera's transform.

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        cameraTransform = Camera.main.transform; // Assumes the main camera is used.
    }

    private void FixedUpdate()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        // Calculate the movement vector relative to the camera's orientation.
        Vector3 forward = cameraTransform.forward;
        Vector3 right = cameraTransform.right;
        forward.y = 0f; // Make sure the direction is flat (no vertical component).
        right.y = 0f;
        forward.Normalize();
        right.Normalize();

        Vector3 movement = (forward * verticalInput + right * horizontalInput).normalized;

        rb.velocity = movement * moveSpeed;
    }
}