#π»βcode-beginner
1 messages Β· Page 83 of 1
because the force is too low and not using Impulse
show us the code again
make it Impulse and set thrust to 100
once you are done
You are also back to using transform.up. Use Vector2
instance.GetComponent<Rigidbody2D>().AddForce(Vector2.up * thrust, ForceMode2D.Impulse);
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?
Time.fixedDeltaTime should not be multiplied into the velocity
but I want it to move not based on framerate though
velocity already handles that
Yes really
okay thanks
that sounds about right now that I think about it
when the object is MOVED based on velocity, the amount moved per individual physics frame would be velocity * Time.fixedDeltaTime. But the physics engine handels that for you automatically
still doing transform.up
Oh
new Vector2(0,1)
Oh, well if it works it works
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
should be the same thing
Except it allocates memory
Still coming back down
true i guess use case would be if you want to consider the current object's rotation as well.
You set gravity scale to 0 on the spawner. It needs to be set on the ball prefab
ohhhh
The spawner also doesn't need a Rigidbody2D at all
Thank you
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.
Rigidbody2D is an object that is simulated by the 2D physics engine
It's a component that allows the object to simulate rigidbody in 2d
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)
wait so can not apply velocity to one without it?
You need one (or a charactercontroller) to register OnTriggerEnter
Velocity is applied to a rigidbody, so no
what do you mean by move via the physics sim is it with the collisions?
The concept of veloicity is easy to recreate without one, but that doesn't mean the object is part of the physics simulation
it's collisions, forces, gravity, etc.
ah okay
When you give a Rigidbody velocity (either by setting it directly, adding forces, or having other objects collide with it) the physics engine moves the object for you
otherwise you have to move everything yourself
You get the whole rigidbody physics bundle (not fake game physics)
like actually using the transform.position to set it right?
yes this just teleports an object to precisely wherever you say
i was wondering what improvements and if my character controller would even work https://pastebin.com/16t9QE1x (its a 2d game btw)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is my first real attempt to make a character controller by myself without a tutorial
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
a powerful website for storing and sharing text and code snippets. completely free and open source.
You can use enums to make states also it will be better if you have multiple methods.
so like make a method for jumping moving crouching sprinting etc
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.
yes it will make you're code organized and easy to read
k thanks
wdym by use enums to make states?
you can use enums to make player states like idle, walking, running etc. than you can use the state to jump, walk etc.
im still not following sorry if im just being dumb right now
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
What is the term for the :Bullet part?
public class HomingBullet : Bullet
I might be wrong but isn't that inheritance? https://learn.unity.com/tutorial/inheritance#
thats the one thhanks
No worries π
this is the current one https://pastebin.com/HpaNNtyf for all of my things to work do they all need to be called in like a void Update or like a void FixedUpdate or smth
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Yeah call your movement methods in void update
https://pastebin.com/DWbXYtcU smth like that would work??
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Yeah personally I'd put the crouch, sprint and jump in update as well but I think that would be fine, I am just a student myself tho so there might be a better way π
bool x = false;
bool y = true;
if(x || y)
{
Console.WriteLine("Either x or y is true. '||' signifies 'or'.");
}
This would print the string.
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
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;
}
}
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?
yes
i agree
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(); )
you can't compare using an interface to SOs or inheritance as they just restrict what members you have access to from a type. the better question is, should you use inheritance vs composition?
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. π
how do i set a sting to a blank value? creating the line " private string ""; " gives me errors
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
or better
private string myString = string.Empty;
i completly forgot abt that part, ive just gotten back into this after like a year of not doing
tnx
You don't start coroutines by calling them, you start them.
StartCoroutine(JumpDelay());
make sure to cache the coroutine so you can stop that specific one manually (if needed) . . .
Have an if statement check a bool before starting the coroutine, and set the bool false inside. Then true when done
just had to place the iniitial one in the start function and have it inside the coroutine start itself
That is one way for sure.
never heard of polymorphism but thanksies for the tips lol
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
"... 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.
when i run this it dosent output anything?
ive never used inputs so i have no clue on what might the issue be
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?
The value is what is passed to the function subscribed
public void OnValueChanged(int index)
I have this in my script
And that function is run whenever the dropdown selection changes
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.
So how can I have that value change respective to the index of the choice selected?
Where do you can read string?
How would I do that?
Someone explained that empty quotations and empty quotations are the same.
im using inputField(TMP) other then that idk
Yep.
Well, you wrote that code. You should know.
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.
The event calls all subscribed methods with the given value
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;
}
Cool. So how can I make this int field in the Inspector disappear and just have it pass in the index of the choice selected? I can't see an option to do that in the Inspector but I'm new to TMP so probably missing something somewhere
OHHH
I just selected the wrong thing
If you want to see the value when it's changed, you can also use https://docs.unity3d.com/Packages/com.unity.textmeshpro@2.0/api/TMPro.TMP_Dropdown.html#TMPro_TMP_Dropdown_value
It depends on which OnValueChanged is selected here. That's my bad.
Where is ReadStringInput called from?
They don't know
Oh yeah, I just read further down
It says 0 references, so....
you need to choose the dynamic method version . . .
Why you check the string in update, not log the string when you get it and check it
whoops, i'm late . . .
ik that part, its being called from on end edit (script)
Yeah, appreciate it though. I should've figured that out much sooner π
Well show that
It says 0 references, so that is odd
It passes a empty string when on end edit
The argument is not the actual text in inputfield
is it this box?
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
ah ok makes sense now, ill see what i can do
what is this called? not sure how to start to fix it
oh ye also the string does appear in this text box, would that be the thing im trying to refrence?
Yes
What is what called?
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?
It may due to floating point error when rendering in z buffer afaik, try to lift the red plane a bit higher,
now I learned its this, but still idk
That is strange. Just to confirm, its not a game object?
all are planes*
Ahh, what is the shader on the object's material?
Unlit Transparent for all
Can you show the inspectors as requested. Also, it looks like they are being moved.
Just don't crop it, show the hierarchy and everything
nothing is moving its happening in scene editor as well
I don't think anything is being moved, but it is strange
@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
To me it clearly looks like the wooden material plane going up and down and side to side (or everything else is doing the opposite)
This is almost definitely not a shader issue though
It would be nice to just see the inspectors...
I put carpet to standard and it fixed, I guess I'll use this
Well, I must have been wrong then.
Is there any reason you were using the Unlit Transparent shader?
Im very new to cameras and shaders
Yeah shaders can do some strange things, never expected that from Unlit Transparent considering I used it a few days ago with no issues
i cant figure out how to get the refrance, i thought i could use "public object refrance;" and then like call the text input string but it dont work
Use [SerializedField] private TextMeshProUGUI textReference (Assuming your using TMPro)
Tmp_inputfield
ill try that
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.
what is serialized field?
It puts the variable in the inspector even if its private, its always best practice to keep variables private if possible.
ah ok tnx
π
so now its giving me an error sayign i cant use it as a string?
First of all, that code is supposed to be SerializeField and not SerializedField, my bad.
What are you trying to use as a string?
so im trying to use the TMP_InputField refrance as a string to compare it to other strings
Use inputReference.text to get the text. I would recommend you to learn about components.
ahh ok tnx
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' π
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?
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
Why is dragging and dropping the best? Is there some practice I have to avoid?
draggin' and droppin is usually best way, try use it when possible
If the component is on the same GameObject as the script, you can do gameObject.GetComponent<TMP_InputField>();
If the component is on another gameobject, then just put it in the inspector with SerializeField
It takes very little cpu usage to formalize that link when you hit play. Anything else is gonna take more. GetComponent is actually about the same cpu usage btw (edit: unless it fails to find it). I was surprised by that
Find uses a lot though, as it just loops over all gameobjects to find the right one
That's good to know. Serializing is easiest of course so I'll just roll with it π
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.
for Runtime components TryGetComponent and clever DI
No code is faster and easier than using code . . .
Not if the component is on the same gameobject
is there a way to save this? i didnt save the work and now its not respoding?
look at unity temp folder online BEFORE you reopen unity. Your scripts saved regardless because they are external to unity
you can get a recent version of your scene back
ye ik scripts save. but its mostly the scene im woried for, also i cant find a folder called unity temp?
nvm i did find it but this is what i see
do i just run that or?
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
Hello, I was working on my game for days and I was stupid and I forgot to save! I was working on it for days and I lost everything after Unity randomly crashed without any warning! How can I recover my scene and prefabs? I reopened the Unity project. Does that mean I canβt recover it anymore? I honestly thought that Unity would have autosave ...
ye i found a tut on yt but tnx
hello, has any one used moonsharp for their project?
b/c i is always zero so the loop runs forever b/c zero is less than 100
thats my guess ;D
ye i figured it out, forgot to add the if statement smh
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)
you cant add parameters to instantiate, but you can add an Init method and just throw whatever parameters u want in there
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?
you would have to call it on whatever script you want to define parameters on
not if you call it right away, there is no frames that will happen between
alright thank you. I will implement it this way
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
if this question is more than "beginner code" let me know
passing minWidth+offset*2 and minHeight+offset*2 to the partitioner?
lemme see if that helps
I think i've already tried this, and while it doesn't make the rooms all puny anymore, it makes it so there's less of them, and the rooms are bigger now as offset increases
i think what i want to happen is that the algo makes the rooms first, and then seperates them out by the offset
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
actually on close inspection, the rooms aren't bigger, but rather there is just less of them because the space in between them are taking up the total dungeon space
if that makes sense
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)
what do you mean by AABB?
you can rotate a rect but not a AABB btw, it has to be aligned with the axis
oh, i see, strange
so i changed it to only add offset (without doubling it)_to both minWidth and minHeight, but i still get some room shrinkage if offset is set too high
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
if the offset is too high than the area have to be large enough....
imagine offset=area width or height
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
yeah exactly
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
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
i would think it has to do with your culling mask on your camera
how does your culling mask look?
Yeeee
My character is super slow with time.deltaTime, how to fix that?
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
k thanks
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
- Would it be better to make a 3rd table that holds just ItemId and ModId that stores all the mods for each item
- 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)
oh no mmo
You should always follow atleast 2NF when implementing a database: https://medium.com/@GeneHFang/normalization-of-database-schema-1st-2nd-and-3rd-normal-forms-3f4d18b857d3
This week I would like to talk about the concept of Database Normalization. Essentially, this is a standardized method of structuringβ¦
So yes, make a third table that stores the item mods
The whole point is avoiding repetitive data, even here
What's your definition of "huge"? MySQL handles comfortably hundreds of millions of rows
don't worry it's not a real MMO π
One can only hope that will not be enough π
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
I feel like databases though are one of the harder things to improve upon once you've made them into a spiderweb
Ah not trying to take shortcuts here, just wondering what the optimal design is
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 π
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
Was it the 3rd form that's ideal but it's unlikely to do so you settle for 2nd form? I forget
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
Code first π π
I believe there are four
But I honestly forgot about the definitions until your question
Mostly it just comes with experience
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
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
Can we grab all asset, dirty them, then SaveAssets just for fun?
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
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?
serializefield private
if two scenes are loaded is it possible to reference an object in one scene in the other
yes
all previous objects are destroyed unless they are in ddol scene or the scene is loaded as additive
Oh mb
There are solutions out there to allow cross scene references, like this one https://github.com/Unity-Technologies/guid-based-reference
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?
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
Nvm I found the solution, I put the sound on void update which means the sound literally repeats every frame
I think it can be fixed with animation event
help me about this one anyne pls
but where are you calling htis methods
to take damage
does it print to console the debug log?
yeah it does but i want it that it shows in the screen also
that it takes damage and full health reduces
The concept you're looking for is scrolling combat text. There's usually a few tutorials on that on youtube if you look about.
did you reference the text in the inspector?
also don't use Text its obsolete
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
yes
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??
wdym general input system
there is no such thing
it's either the old input system (which is not recommended) and the new one
Why would you delete the project?
You can just change the input system
old
its much tricky
Very simple. It's one switch in project settings
we told him that several times
how can i??
noel
Switch Active Input handling in project settings
The only other things would be:
- changing all your code
- removing the input system input module from EventSystem objects and adding the StandaloneInputModule
the first one is matrix
still facing the issue when my objects are colliding with my tree that its validtobebuild. i really don't know how to solve this. would love some help.
What?
If you don't care too much about the absolute shape of it all, I'd just continuously cast and check using overlapbox
how can i do that? @timber tide sorry for asking noobish questions.
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.
do i need a whole new script or jsut add id to my constructable script?\
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
void Update()
{
if(IsBuilding && !CheckForOverlap())
{
//There is no overlap so it's valid to build so build
}
}```
Think of the logic like this
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...?
Always use the profiler
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...
Also consider if accessing the db is the limiting factor. Adding to a list can have some cost if done frequently due to garbage collection but can be avoided by presetting a capacity large enough to accommodate what's to be added.
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?
reference the script and its type directly
[SerializedField] private MyScript myScript
I forgot to mention that I'm getting the GameObject as a Collider via a Cast
But using a LayerMask, I know what I'm getting
then get component is fine, but I would just replace it to TryGetComponent. Which is essentially the same thing but with a null check
Alright. Thanks π
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?
What exactly is Fish supposed to be?
Either way, just define a != operator for your Fish type and you're good
I guess this needs an explicit comparison added if you really want this
I would advice you instead compare an inner property
Fish is a struct
Then define a != operator
How would I do that?
or just make it a class..
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
I could do that
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
structs can most def have methods lol
If you don't know what a reference is I HIGHLY suggest you stop using structs
Just use classes
major difference is that structs are Value type
completely different ballgame how they get stored
major reason structs can never be null but class can
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.
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
if you swap to class you can directly do == nd != on class itself
I know, but I'm not sure if that's the better than comparing a unique property of the class
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
with no collider triggers and just the CheckOverlap function i still can't build and its not working. π¦
constructable (what i want to change to detect isValidToBeBuilt;) :
https://gdl.space/leqigobano.cs
construction manager:
https://gdl.space/gemufeqebu.cs
Ignore the bools and just compare everything each update
oh wait sorry let me refine this
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?
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
do i need to change the IsBuilding to isValidPlacement?
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.
but i have different objects to use in my constructionholder
yes this is a problem aswell. i can build through the ground
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
If you've got a specific problem do post, but with what you got there I assume you've got a good idea.
Now that some more people are waking up, just bumping this up to see if anyone has any suggestions on fixes to my issue here
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
make sure you follow all these !vscode
!vscode
!vscode
Hey I've been curious why some people prefer VSC over VS. Mind letting me know why you chose VSC?
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
show your packages real quick
screenshot console window in unity as well
it is a new console nothing is in it yet
alr did you try hitting Regen Project Files inside External tools ?
this
yup
nothing changed
open the script from unity, do you see anything in Output in VSC?
Did you close vsc before clicking regenerate?
yea
what is that
its the solution file inside your project
alr
you tried restarting already?
yea
try to open the whole folder In VSCode
i have
clear output, do it again.
anything in output ?
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 ?
not likely lol show code
yes sure just a sec
I recommend you just start using VS
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
I can already tell that if it's an input field then the type is wrong
but it happens on vs aswell
[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 ?
Yep. Input fields are TMP_InputField
lol whyy would someone do this..
well i will check what it is haha i have started with unity few days ago
That text field wouldn't happen to be the one attached to an input box would it?
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
yes it does actually
TMP_InputField already excludes that character
The more general type picks up the entire element which includes a control character which is possibly the caret position
It didn't two weeks ago, but maybe a newer versions come out since then? Or I was on an older one
The TextComponent is the component i take the text from
thanks it works perfectly @polar acorn
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
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
Why you can't, how are you going to determine the raycasts origin then
Not sure why you need a SO for that
You can have SO for Raycast data's like range, layermask etc
I'm making a buildingSystem, and I have various furnitues, I only want the player to be able to place them if the 3 raycast returns true (it checks a layermask)
But why would you do Raycast in there
Make a mono behaviour like building detector
Don't do it in the so
Use a list of vectors, or a list of structs that hold a position vec and a direction vec
That's not rly a good approach
I'm not using the SO
Better to use the transforms so you can rotate them and position easily
And just do forward as the direction
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
I don't see how is using scriptable objects blocking him to make 3 transform as he said
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
Use 3 transforms that you put in the player π€·ββοΈ
Then raycast from each of those. Can put them in a list/array and do it in a loop too
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
You could keep them separate but add a method like AddKnockBack to the movement script that you can call from the shooting script
is there a way to compare all the entries in a list and pick the highest/lowest one?
ofc.
imo linq quickest
thanks
sure, write a for loop.
Hi all, how can I have objects I pick up keep their rotation prior to being picked up?
https://i.gyazo.com/0dbe666dc643e813c8ce7d1a36da8d94.gif
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
so just remove the MoveRotation?
I still want it to rotate with the camera
cant you just parent it to player /cam then?
true. you can try using just velocity to move it from prev pos - new pos
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
Can you not just disable physics on the object when you pick it up and re-enable when you drop it?
its ugly because it goes through walls
I still want it to move relative to the camera, just not reset the rotation once picked up
you tried setting holdarea.rotation to pickup item rotation first?
just do a comparison check on all three and update a variable is lower?
Might be wrong, but record the rotation, parent to player, set the rotation to the recorded rotation?
Holdarea rotation is just a get of a transform attached to where my characters holds stuff
Is it possible to set a gameobject as a variable?
ya lol
lol
not very useful but sure
That might work
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
oh
I mostly just want to set another gameobject in the scene as a variable whos position I can track
Yaaay, I helped. lol.
yeah valid I just used to use Transform if they dont have a script on them
it don't matter they both work fine , if they do have scripts on them though mind as well reference that
@novel shoal Try increasing/decreasing the mass on the rigidbody.
i am literally doing what it does in the learn.unity pathway, but there the object jumps, here it doesn't
And the drag maybe
i tried both with 1 and 70
same result
(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
Are you setting velocity somewhere else? Or is the rb kinematic?
now it works, and i have no idea why, i literally changed nothing
@queen adder thats kinda doing what i said no? with an extra step?
Yeah what you said worked
oh ok lol
navarone new pfp lol
do i need to reference the scripts as well even if I just want the transform?
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
answer yourself
no but if you have script on them and a refence to it already, you can just do .transform
every MonoBehaviour has access to their .gameObject and .transform respectively
If you just want the Transform then just use Transform directly. No need for GameObject as an intermediary
how do you use the transform directly?
π yeah Transform is a type as well
I
Still have absolutely no idea how making a transform variable will help me find the transform value of another game object
you assign it to the object
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
I know what transform is
time for unity courses
I already did those
then you skipped the most important parts
go again
Basic variable assignment and referencing is like the most important thing
I'm confused how making a reference to a Transform would NOT help you access that objects transform..
This is a great resource that may help! I always recommend it
https://unity.huh.how/programming/references
What they are discussing is a "serialized reference". Also called a "drag and drop" reference pretty often
yeah wait a moment talking with someone I can actually understand
(it's probably ChatGPT)
No its a person who speaks slovak and codes
Ah there's a language barrier
Yeah- and yeah it was simple just had no idea what you were saying because I cannot understand english well at midnight, sorry
People can live different places...
no
Discord user discovers there are, in fact, people living in multiple timezones. π€―
cringe
Breaking news: People can sometimes live outside of the place they are from
breaking news discord users are mostly cringy af
No, that's apparantly cringy π€‘
God.. some people
not living in slovakia rn
georgia instead
wait, so there are other timezones than CET? (jk, don't take me seriously)
Our top story tonight: local discord user in straight damage control mode trying desperately to pretend they aren't upset
get some pills mate and chill damn
Telling people they are cringe while looking up the time to see if they were lying or not. Ironic
i didin't look anything but k π
Irony at its highest lmfao. But yeah, I'm done
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
When you say patrol point, do you mean the variable itself has an extreme value or that the nav mesh is going somewhere you don't expect based on the value of the patrol point variable
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
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
how can i make it so random range doesnt generate same values
Why it doesnt work
U is float btw
because 0.001 is a double
iam stupid sorry
make a list of your numbers, chose from that list, remove a number from the list when selected
im very new to coding how should i do that
what about it do you not understand?
transform.Translate(Vector3.leftTime.deltaTimespeed);
this doesn't move an object wtf
how do i do list
(the speed is a public float 30f)
now you need to go look at the C# docs on List
public typeofthelist[] nameofthelist
no that is an array not a List
oh lol
is it possible to use Contains
but the inverse i.e check if it doesn't contain x?
Contains returns a bool so, yes
oh thanks didnt know that
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
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
localPosition and localRotation?
oh
uh just a second
i cant find it give me a few
do i need to run a command to grab that?
k ill find it out
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
solid colliders π
is that a joke XD
nah
oh thanks haha
but i do question whether it'd be better to just have a bigger circle overlap the player and some of their hands
i see what you mean but for accuracy sake this seems to work best for me right now
let me show you what I mean
Oh i see what you mean now
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
yeah ill do that thanks
thanks haha
like this?
i kinda am thinking I remove the gun colider all together maybe
reminds me of these guys π
sometimes came with a school bus that looked like an egg carton π
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 π
perfect!
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
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 π
mmhm
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?
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?
normally happens when the navmesh agent is too far from the ground
Let me show u the navmesh bake
Your enemies are under a parent object, that might be the cause?
AddRelativeForce with transform.up is wrong
AddRelativeForce is meant to be used with a local direction vector but transform.up is a world space vector. Use either:
AddForce(transform.up) or AddRelativeForce(Vector3.up);
Oh yeah. How do I fix the robot floating. I'm using transform.LookAt.
adjust the LookAt position to be at the same y position as the robot
Wait no the error still shows
e.g.
Vector3 lookAtMe = target.position;
lookAtMe.y = robot.transform.position.y;
robot.transform.LookAt(lookAtMe);```
Do you have a navmesh built for that AI type?
Wdym
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
Thank you
That orange lines is the navmesh bake
looks like its up above the ground plane to me
No I moved it
I don't see the the baked navmesh π€
And it's still got error
Oh, thank you
a properly baked mesh should appear blue when in the navigation panel
@forest karma Just to confirm, the Robot is type Humanoid?
Click "Bake" again, it doesn't look like it is baked
@forest karma What is the layer on your ground?
i need to fiddle with the new versions of unity..
im out of hte loop on navmesh's and their new functionallity
!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
@forest karma Hmm, what if you tried setting it to include all layers in the NavMeshSurface?
Static isn't needed in the newer AI version
2022.x
That just breaks it
Can you be more specific please?
cool, thnx
Is it giving you that error you had before?
Yes
How is the enemy moving if its unable to find the navmesh π€
It doesn't move anymore when I sid everything for layers
Was it moving before?
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
Can you select NavMeshBake object and send another picture please
Also, are you using the new or old AI system?
It seems like an issue with the NavMeshSurface since it should be showing blue on the ground
You could try, but it shouldn't matter
it should be neither technically
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
This?
Change it to "In Project" or "Unity Registry" and search again
Nothing showing lol
Wait I imported the navmesh file by dragging it into my project
yeah they are using the 1.0 version before it was a package that needed to be installed separately
From github
Is AI Navigation 2.0 available on Unity 2021?
@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
the old navigation is weird I had so many issues getting it to work properly
You should still use the updated AI Navigation π¬
Is Static ticked on for the ground game object?
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?
I only see a white box... But that looks correct, hmm
Actually it may be orange
@forest karma I'm really not sure what is causing that error, everything looks correct.
hi, any idea why my obj is disappearing? when i press click
nvm, i forgot to set z to 0
This doesnt seem to work
can't be disappearing.. its just appearing somewhere else
in playmode select the object in the hierarchy and press F it will focus on it and show u where it is
They figured it out
i solved mysellf
u can debug the transform position and figure out where its going and why
np good stuff
How can I make my robot have the correct y position when looking at my player to shoot
use the player's Y position to look at
private void AttackPlayer()
{
enemyAI.SetDestination(transform.position);//Enemy will stop moving when attacking
transform.LookAt(player);//Enemy will look at the player when attacking
You need to rotate just the Y axis not all 3
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
how
Try this,
transform.LookAt(new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z));```
u can manually change individual properties..
like transform.position.x = floatValue; for example
Try this.
transform.LookAt(new Vector3(transform.position.x, player.transform.position.y, transform.position.z));```
^ my favorite little hack
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?
Yeah, but i dont like the new line of code since it ruins my projectile shooting now
Yeah I believe that is what I'm also doing although it didn't seem to work for him.
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
a powerful website for storing and sharing text and code snippets. completely free and open source.
Thats the whole code if u wantd to see it
so when the parent looks forward.. the enemy gets rotated facing downards
@forest karma Check the NavMeshAgent collision, you may need to change the offset or scale
asking just one more time to see if anyone has any suggestions, if not, that's fair
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.
everyone starts with zero unity experience..
if u have code experience at all u got a headstart
sounds like you have more experience than those with no coding knowledge so you're ahead of the curve
You should learn the basics of coding/C#, but other than that you don't need any. Unity can be a great place to start π
Yea ur right
Im not sure how to fix it in blender though
You could create a parent game object
thats outside my knowledge.. id suggest posting in a more advanced room.. or maybe making a unity thread about it..
okay, thank you! honestly wasnβt sure. π
it is parented
since its a whole system that you have already
starting unity without knowledge of constructors and objects is asking to fail
you learn thru failures tho
am i... ready to move up to #archived-code-general ???
How so?

imagine trying a new language out and you're wondering how to instantiate objects
Carby = level up
lol, for a complex system like room generation.. u probably would have more luck there tbh
Yes, I don't think any of us understand what you're trying to do haha
fair enough, i'll post there
should i delete my post here? i don't wanna get done in for cross posting
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
I don't think it would be cross-posting considering its been 8+ hours since you posted that.
ya, it'll be good and buried by the time u get an answer most likely lol
i mean..
shouldn't be too hard imo
the terminology would be trickier.. but u learn that as u expose urself to the mechanics
yeah i think understanding objects and instantiation is pretty easy, it's just that beginners get jumbled up by terms
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
this is a code channel
perhaps you want #πβanimation
Thanks!
if i have scriptable objects called ItemData
how do i find all of them here
is it even possible?
theres no scriptable objects
@tender stag A ScriptableObject is a Script. It would be under Script
i need like these
not the actual scripts
yeah i dont think its possible
nevermind
if you want to find instances of that kind of object, then search t:ItemData
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?
Perhaps events are being consumed
or maybe can see if current gameobject that's selected isn't changing if you're using other events
Hmm. I shall dig into it more.
I was sort of hoping somoene was going to say "Yeah thats just unity being unity."
There are always things to do which can circumvent stuff. It's all about figuring it out.
I do dislike these interfaces but I cant be bothered implementing them myself. Especially the drag interfaces.
Dug into it more, its actually OnPointerUp thats being called for some reason...
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 ! π
They're just textures, why do you need multiple shaders?
Well I have a good grass shader I design, same for water and I canβt applied both to a single mesh.
Water and grass should probably be a separate object/mesh.
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
Found a fix for this, which is by far the dumbest thing.. but.. Adding IDragHandler and public void OnDrag(PointerEventData eventData) { } (Even if its empty) fixes the problem.
So, it was indeed, a "Unity being Unity" problem.
Would you be able to help me ?
you sure it's not just vertex coloring parts of your mesh?
what makes this a shader and not a surface texture / vertex coloring
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
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
You can do that with submeshes yeah. But that isn't really different from generating several separate meshes.
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
is this component attached to a UI object or a world space object?
and you have an event system in the scene?
yes
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
deactivated every other ui canvas and made sure anything else was either off or out of the way still doesnt register my clicks
and have you checked the preview window of the EventSystem to see if it is detecting anything?
i dont think its detecting anything
its detecting an interaction prompt ui i have but not the book?
does your canvas have a GraphicsRaycaster?
yea
then show the event system's preview window while you try to select that object at runtime
no way for detect if a gameobject is colliding something in this exact moment (not with onCollisionEnter/Exit) other then rayCast?
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
correct, if you want to check for current/potential collisions outside of OnCollisionEnter/Exit then you'd use a physics query like a raycast, boxcast, overlapsphere, etc.
or you could keep track of every object that it comes into contact with in OnCollisionEnter/Exit
You could use OverlapSphere depending on your needs
I guess that the raycast is the most light function, right?
Yes, raycast is most likely most performant.
i need help, i keep pressing 'W' but for some reason it gets reversed if i look the opposite direction
Can you show me your code please.
Yes
I just need your movement code
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
}
}
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
ahh my bad
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
}```
Which line is line 66?
You were missing a comma, I added the comma in the code above
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?
What is your error?
there is no error but i cant look around
@round sentinel I updated this code, try it again.
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);
}
}
You need to add a rotationY to the Quaternion.Euler()
would i make another private float
it says this now
Yep
Please read the error. It says you need to assign a CharacterController to characterController, I assume in the inspector.
i kind of suck at this whole coding thing, i added a rotationY then put Quaternion.Euler(rotationX, rotationY, 0f);
i dont know where : (
@austere monolith I have updated this code, try it. Also what is transform.Rotate(Vector3.up * mouseX); for?
I checked your code again and you're doing it in the Start(). Did you remove the Start() function?
looking i mean
This line does the rotating π€
Camera.main.transform.localRotation = Quaternion.Euler(rotationX, rotationY, 0f);```
I made a mistake, I have updated the code.
its to rotate the camera horizontally
This code rotates the camera though. You shouldn't be rotating the camera twice like you currently are.
Just comment that line out, and test without it. I don't think its needed.
You're welcome.
wait what
sorry for that, i replaced my code with urs but its still the same i dont know why
another error XD
The code I provided didn't include the Start function, your code already had that, I just provided an updated Update() function.
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;
}
}
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
@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;
}
}```
You're welcome.
Is there a reason you're using RIgidBody instead of CharacterController for movement?
the built in gravity
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.
ill go learn how to do it in character controller
You do what you want, it's your game.
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);
}
}```
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?
Did you add a Character Controller component to your game object?
yes
Send me the error please.
anyone know why my player is just falling through the map
Does both the player and ground have colliders?
yeah
do you have a collider on your player, the ground needs a collider, you needto use physics for player movement
@amber spruce What are the Layers on both the players and ground?
are you using character controller or rigidbody
i found the issue
Those wouldn't affect collisions
it was smth with the character controller
aight
Can you try copying the code I sent above. You may have copied it before I edited it.
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;
}
}