#💻┃code-beginner
1 messages · Page 642 of 1
Yeah unity isn't great for this kind of stuff, maybe i can write a simple custom editor to handle this, or store card code inside some other file formats
you can store it in classes pretty fine
you just don't need to handle the logic in editor
Hello. There is no assymetric limit for a Configurable Joint ? I'm trying to do a drawer in VR, but the drawer can be "pushed" in the wall
This example isn't amazing since it needs abit of context but here's a snippet from a card game project i messed with
[CreateAssetMenu(fileName = "Hook", menuName = "ScriptableObjects/Moves/Hook", order = 1)]
public class Hook : MoveData
{
public override IEnumerator OnActivate(MoveInfo moveInfo)
{
//moveInfo.enemy.player.MoveCardPosition(GetTarget(moveInfo), 0);
List<Act> acts = GetActs(moveInfo);
acts[0].InvokeAct();
yield return new WaitForSeconds(0.5f);
EndMove(moveInfo);
}
public override List<Card> GetTargets(MoveInfo moveInfo)
{
return (new List<Card>() { moveInfo.enemy.hand.Last() });
}
public override List<Act> GetActs(MoveInfo moveInfo)
{
Card target = GetTargets(moveInfo).First();
SetPositionAct setPositionAct = new SetPositionAct(moveInfo.card, target, 0);
return (new List<Act>() { setPositionAct });
}
}
where you can reference this Hook move/effect (imagine like a pokemon move) in unity super easy
but the actual logic of it is done in the class code directly
(getting the target the move is gonna be used on is seperated because i wanted to be able to preview the attack without actually running it)
one thing i highly suggest for this kinda pattern is whipping up a little script template too
if you put specifically named files in /Assets/ScriptTemplates/ you can set up your own default scripts like how the default one gives you the start and awake function
helps skip annoyingly making a new monoscript doing all the writing then making the new scriptableobject etc.
omg this is great, thanks for the info
eg. Assets/ScriptTemplates/01-Script Templates__New Move-NewMoveData.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
[CreateAssetMenu(fileName = "#SCRIPTNAME#", menuName = "ScriptableObjects/Moves/#SCRIPTNAME#", order = 1)]
public class #SCRIPTNAME# : MoveData
{
public override IEnumerator OnActivate(MoveInfo moveInfo)
{
yield return new WaitForSeconds(0.5f);
EndMove(moveInfo);
}
}
uses the name you give the cs file to populate the createassetmenu attribute too
gorgeous tech
lol i can't send a cyberpunk gif
Hey, no ideas for that ?
not sure but if there isnt assymetric limit u could alwys change it dynamically dependent on whether ur opening or closing the drawer
What do you mean ? Actually limit while opening work
Which for movement rigidbody or controller?
They both work, you should consider what kind of movement you want in order to make a decision.
rigidbody
like osteel said, they both work
I followed a tutorial using controller but I got problem, so i thought i should use rigidbody but that was worse cause i realised controller has a lot of things rigidbody doesn't e.g u can walk on stairs smoothly unlike rigidbody. Anyways this is the script that I made it has working gravity
Isgrounded = Physics.CheckSphere(GroundCheck.position, GroundDistance,groundmask);
TouchedUp = Physics.CheckSphere(UpCheck.position, GroundDistance,groundmask);
if (TouchedUp)
{
velocity.y += gravity + Time.deltaTime;
}
if (Isgrounded && velocity.y > 0 )
{
velocity.y -= gravity * Time.deltaTime * 5 ;
}
if (!Isgrounded )
{
velocity.y += gravity * Time.deltaTime ;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && Isgrounded)
{
velocity.y = MathF.Sqrt(JumpHeight * -2 * gravity);
}
controller.Move(velocity * Time.deltaTime);
}
is there Anyway i can turn the code to unity in discord or do i have to just take a ss?
The problem is I feel like this is not the best way to handle gravity is it?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Each one has things they're good at and you've nailed em both. CC is great at handling slopes where Rigidbody really struggles, and Rigidbodies make gravity completely free, unlike the CC where it's a bit shoddy.
Just gonna come down to which one's the one you wanna optimize for.
Thanks
I have code that moves a collider down in a loop, adjusting the y position by 0.1 each time, and checks for collisions to determine the highest and lowest points of (a section of) a mesh. However, it seems that physics (collision) calculations aren't being registered during the loop, even though they work in a coroutine or update loop. The issue is that I need this to happen within a single frame. Any suggestions?
Figured it out, didn't know about Physics.SyncTransforms() and Physics.Simulate()
using Unity.VisualScripting;
using UnityEditor.SearchService;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DistanceScript : MonoBehaviour
{
private Rigidbody2D rigidBody;
private Slider powerSlider;
private PointerEventData eventData;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
Debug.Log("Added RigidBody");
powerSlider = GetComponentInParent<Slider>();
Debug.Log("Added Power Slider");
}
// Update is called once per frame
void Update()
{
powerSlider.OnDrag(eventData);
if(eventData.dragging)
{
Vector3 pos;
Quaternion rot;
rigidBody.transform.GetPositionAndRotation(out pos, out rot);
Debug.Log("Recieved position of Cue");
rigidBody.MovePosition(new Vector3(pos.x + powerSlider.value, pos.y, pos.z));
Debug.Log("Moved Cue");
}
}
}
hey guys, why does this code give me 999+ errors ||sorry, im noob me never use unity||
which is line 27
powerSlider.OnDrag(eventData);
then powerSlider is null which means this object does not have a Slider component in any of its ancestors, and why would it if it has a rigidbody2d on it
finally no more stupid std::couts and breakpoints 😔
how do I get the slider then
get a reference to the existing slider object: https://unity.huh.how/references
preferably using the Serialized references option
all of the things attached to the gameobjects are, yes. why?
instead of constantly lamenting how you have no idea what you are doing, why not go make an effort to learn using some actual learning materials instead of attempting to brute force your way through this
here's some good learning materials !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Ok ||After I make the slider slide properly just as an experiment||
Yay it worked 😄
can someone please help me i made a shader in the shader graph but it’s stretching on the bootom and top
ik how to make them
but i’m not logged in on the laptop
bc i’m not home and it’s my brothers laptop
so i dont want him to have access to my discord
it's also a website you can visit. but still, the question belongs in #archived-shaders
so.. logout after..
So I wanna learn the coding side of game development, but I don't really wanna learn how to make the maps etc...
How would I do this?
Procedural map generation 
noise solves all problems
hi guys so i just installed unity and opened microsoft visual and i wanted to get key input so i typed
if (Input.GetKeyDown(keycode.Space) == true)
and i got an error saying the name keycode does not exist in the current context
wha does that mean😭
It means keycode does not exist in the current context
There's nothing called keycode
oh then how do people get key input then
Yes
KeyCode exists. keycode does not
Make sure your !IDE is configured so that it suggests the correct spellings for things
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Is there a preset for Unity3D camera controls or does it need to all be coded manually?
(For instance, making the player's mouse control the pitch and yaw, the scroll wheel change the offset from the player, having the camera offset change depending on obstructions, etc)
Cinemachine has camera avoidance but the other stuff is relevent on your own implementation. There is templates out there by unity that do have some of that written up though
While following along with this tutorial it won't let me add a 1x1 pixel image to the source image like he does at the 1minute mark. How do I turn it into a sprite asset to it will be accepted?
https://youtu.be/gHdXkGsqnlw?si=yVoJ0AO4E5ewoY4U
Make sure the image type is Sprite (2D or UI) and is set to "Single" not multiple
hey! I was working on a new project, and everything was working fine. I restarted unity for an unrelated bug, and while it fixed that, all my key binds stopped working. Can anyone help me out? (The project is in 3d if that changes anything)
How do I create a simple 'Tile' to use for my terrain generation?
I have a Tile Palette and I added my sprite in it, now what do I do?
Why cant i make a project
I don't know much, but I might be able to help. Can you please elaborate on your question?
And take it to #💻┃unity-talk too
look
sorry no idea
For future reference pay attention to what channel you're asking in. This question has nothing to do with code.
To answer your question, this is likely due to a failed or incomplete editor installation. Try reinstalling and pay attention to any issue during the installation.
kk
I wish someone helped me for tiles....
my project is like dead. when i went to reopen it im getting a ton of errors that shoudln't be there 0.o
then it prompts me to enter safe mode
Start with solving the errors. If you have difficulty understanding them share the details of an error.
I have a player that can mine stones. the player has a capsule collider and a hitZone box collider as a child game object, you can see to the right of him in this image. Each stone has a box collider. When I swing the pickaxe to mine stone, it seems like it's detecting the player's capsule collider, not the hitZone collider. Here's my function for mining stone, why does it still count this as a hit even though the player is facing away and what can I do to fix that?
public void MineStone()
{
Collider2D[] stones = Physics2D.OverlapCircleAll(hitZone.position, weaponRange, stoneLayer);
if(stones.Length > 0)
{
// always mine basic stones
if(stones[0].GetComponent<Stone>().stoneType == "b")
{
stones[0].GetComponent<Stone>().TakeDamage();
}
// only mine if player has diamond ability
else if(gameManager.canMineDiamond && stones[0].GetComponent<Stone>().stoneType == "d")
{
stones[0].GetComponent<Stone>().TakeDamage();
}
}
}
I have weaponRange set to 0.5f. I thought maybe the range was just too big at first, but I'm not sure that's the problem anymore
Well the overlap circle probably detects the hit zone collider, since that's where it's being executed.
And since that's parented to the player(and probably doesn't have an rb of its own), the player is considered an owner of that collider
If your hit box collider doesn't server any purpose at all, perhaps just remove.
you're right that I have no rb on hitZone
the hitZone collider is so I mine what's in front of my and not the capsule hugging the player's body
front of me*
Is there an actual function that it serves? Is it supposed to collide with something and you detect these collisions somewhere?
Because from the code you shared, it looks redundant to me.
I was thinking there'd ultimately be 4 positions the hitZone collider would go so the player could choose to mine above/below/left/right instead of using the player's body coming into contact
if there's a stone above you and to the left, if you just use the player's capsule collider here, how do you choose to mine one stone over the other?
Adding debugs made me find the keybind is being detected (once) but then is ignored again. the associated code is not being activated at all
But you're using an overlap anyway. It's not like you're using that box collider. It wouldn't be any different without the box collider. At least from what I can see in your setup.
You'll need to share some info on your setup and code. And how you debug it.
If it’s detecting the hit zone collider, wouldn’t that indicate that it is on the same layer as the stones? Why not just make them separate layers?
Or you need to correct your layer mask being passed into the overlap function
Also you could just do a loop instead of grabbing the first index and only proceed with logic if GetComponent<Stone> returns a valid reference.
Then you would just skip over the hitbox
This is hard to explain but i have a gameobject ui for the background of my shop
then i have a empty object with just the grid layout group on that background
then i got my own settings and allignemnets and i am trying to make a scroll wheel on the side
i added scrollbar to scene and on background i put a scroll rect and applied the vertical scrollbar to the scrollbar i made before
but i cant scroll down the bar of the scroll is just covering the whole thing as if there isnt enough
i tried making abunch of buttons so there shuold be something to scroll to but nothing
there are good youtube videos on scroll wheels
yeah i figured it out it was as simple as changing the height on the grid
I'm running into an issue and I dont know what to do to get this to work. So I want to rotate my character on a top down game to face my coursor. But I want to make the character have a set turn speed so you cant turn instantly my pointing the character at the mouse location. So I want to use Quaternion.Lerp to lerp the rotation towards my mouse loaction. I got the mouse position and the rotation and everything working but instead of just the Z rotation rotating the character to face left and right, It also rotates the x and y axis making the character turn into like a paper character. So it turns the sprite to the side making it thin af haha.
Heres the code for the script, all of the transforms, mainCamera and everthing is set up correctly
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class FaceMouse : MonoBehaviour
{
Vector3 relativePosition;
//Where the nose should be pointing
Quaternion targetRotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);
public Transform target;
public float turnSpeed = 0.1f;
// Update is called once per frame
void Update()
{
faceMouse();
}
void faceMouse()
{
relativePosition = target.position - transform.position;
targetRotation = Quaternion.LookRotation(relativePosition);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * turnSpeed);
//transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.time * turnSpeed);
// Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
}
}
Thats the transform for the player, those numbers change. Up and down changes the x rotation, left and right is y, and it looks like the z rotation is moving but its slow compared to the others
Like is there a way to just specify the rotation from the from and to point to just z? like dont rotate x or y, just z with an interpolation
from the from and to point to
This bit makes no sense.
But if you just want to rotate around Z, only change the value of Z
Yeah, I want to rotate Z its just that I want it interpolated and I don't know how to do it other that trying to use Quaternion.Lerp. is there a way to interpolate that z axis using the location of your mouse as the target and the center of the character as the from point?
I'll re-word it haha. so in the picture, I want my character to rotate smoothly to the green box (Green box repersents my cursor)
oh, it's 2d and you just want to look at the mouse cursor
tones of solutions for this online
I've tried searching for 2 hours, I couldn't find any myself. I could just be dumb though
Issue with this is your character is looking straight at the cursor. if you move the coursor faster, the charcter turns faster. I want to interpolate it at a set speed so if I move my cursor to turn the character, if I move it realy quickly behind him the character will slowly turn at either a set or interpolated speed
Because in the documentation for Quaternion, all of them if it applies just snaps the character to cursor. The only way to get a smooth turn is from Quaternion.Lerp or Quaternion.Slerp I think its called
But both of those turn my character on the x and y axis when I only want the z axis to rotate
yes, lerp and slerp
you can lerp/ slerp a single value and feed that into a quaternion rotation
How can I do that?
Yes. go to how to lerp roation. you se how one face of the cube is rotating on the x, y, and z axis? I want to rotate it just on the z axis as in the picture
Or heres a better explination. I want him to rotate on the z axis over a period of time based off of the transform location of my cursor
by making sure X and Y are 0..
You can use rotate towards over lerp cause I think lerp will run into problems of finding the shortest angle of rotation
slerp I think gets over that problem though
Im trying to do it here and my guy is just not rotating XD
hey so im wanting to make a roguelike game did the movement and basic attacking but how do i make it so i can pick up different weapons and store them in your inventory
Unity also has a great tutorial on Lerping: https://learn.unity.com/tutorial/linear-interpolation. You can try the previous course (LookAt) first to gather good knowledge about the concepts!
Larping?
Also, how easy would it be to make it so that the game would take a png file and from it create models or prefabs from it
Like how the clausewitz engine works for pdx map games if that helps
I end up having way too many scripts on my player object because of modularity - what is the best approach so that this doesnt get out of hand. Create an empty GO for "Movement" with all the movement scripts attached - and add this to the player object?
lerping, from __l__inear int__erp__olation
its hard to suggest much here, especially if some of those objects expect to move the current transform or do GetComponent calls. Moving it doesnt change the amount of scripts, just where they are and could be equally annoying to go through later. Maybe some of those classes couldve not been monobehaviour, and just been plain c# classes instead
thats definitely one downside for going full "single responsibility" while trying to make it easy to setup in inspector
Can chop up movement and make a Motor class that the base transform references. These could just be c# classes, but if you want a way to decouple everything you'd make it a mono and child it to the base transform and just use component workflow
For example
PlayerTransform
-> Components
-> Motor```
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Hi! I'm a beginner recreating Pong as my first project. In Pong, the ball is bounced at an angle from the paddle based on which of 7 invisible sections of the paddle the ball hits. So, I've given my paddle 7 child objects with colliders and wrote the following script for the ball itself.
https://paste.mod.gg/jjsjlghkqilk/0
Yet the ball still bounces off of the paddle the same way it did before I wrote this. I think it's checking the parent object's name instead of the child object since the parent (the paddle) has a rigidbody and the child collider doesn't? How can I have this script on the ball reference which of the paddle's 7 child colliders it hit?
A tool for sharing your source code with the world!
confirm what it's hitting first, by logging it out
Debug.Log($"Hit collider: {col.collider.name}");
Oh cool, that helped me figure out that the problem actually comes from hitting two sections at the same time, which it does most of the time.
It works as intended if it hits just one
I think I can solve this
Another way to do it would be instead of using 7 colliders, use just one collider and calculate the section based on which part of the collider the ball hits
using getcontact?
yes
This is a little more on the design side but i wanted to make sure i understand things correctly: I'm making a little rpg in which each class has its own stats, sprite, and moves. I know ScriptableObjects are good for holding data like that, but I've heard varying things about their usage when holding functions (which would be the moves in this case) could all of this be handled using a ScriptableObject or would I have to use something else along with it to store moves fully?
I don't think I'd put movement in an SO, but you certainly could
You'd have to always pass in the rb/ transform/ whatever is being moved to that method
moves as in skills/usable abilities
probably should have been clearer
every move just takes in a source Agent and target Agent
You could totally do it in the SO yeah
really just depends on the context but its def not out of the question imo
in this case i'd probably have a seperate move SO that you plug into the unit
Where would the actual move function go in that case though?
in the move so
That way the moves aren't directly built into the classes
even if you end up doing it that way by nature of the games design
put it wherever it makes sense for your game
and results in the least amount of code
I guess I'm just a little confused on where the code goes in this case, I assume a separate (static?) script would have to be made for each move and then passed into an SO (instance?) for that specific move?
In the case people tend to use (and what i was suggesting) you'd probably have a scriptableobject script and an instance of said script per move
but there's no single answer so
As you'll have different skills... you'd probably be better off having a base/ abstract class called Skill which has the required methods (attack, defend, etc) and all the other skills inherit from that. The only SO involvement would be to give different required values to the skill
idk personally at that point knowing that the skills are gonna need display strings, sprites etc. etc. it feels easier just to do that directly through SO's rather than base classes
I think you'd end up with too much unrelated code sharing an SO class
SOs are fine if you want to move similar data around the editor, otherwise serializing structs/classes works fine too
Benefits of SOs:
Easy data sharing, decouples code, can be seralized as lesser derived classes.
Cons of SOs:
Bloats up project with asset files
Benefits of Serializing Classes:
Singular data embeds right into the prefab
No asset bloat
Cons of Serializing Classes:
Can't cross references instances on the editor
Nesting classes can eventually make it unmanagable on the editor/gui
Type is hardcoded; need to change in code if you want to serialize a lesser derived type
thank you all for the help 👍
Personally agree to disagree on 2 files per move being bloat but maybe there’s some games i’m not considering
Not being able to easily pick the type per instance for serialized classes is def a pretty major con if the game isn’t directly building in moves to classes though
I've had a skill system where each little component had a SO dependency. Every skill needed its own directory for how much data was floating around
I mean that makes sense though no?
It's fine if you prefer to do things that way
I get that it might have initially unideal editing usage at scale but more objectively I think it makes sense to have each of those pieces of content be defined by a separate file
Really the big take away that no one really considers is the nesting problem of serialize classes. You can open up an SO alone and easily references other SOs without making the GUI impossible to navigate.
That and nested classes have serialization problems about 2-3 nests deep
First it stops considering default values, then it just outright wont serialize
Wouldn't nest classes for this sort of thing anyway
like Pokemon for example i'd imagine there would be
An SO for the Pokemon that holds
An SO for the type
An SO for the ability
1-4 SO's for the move
An SO for the held item
So, let's say I have a list of these POCOs called Character.
If I call a method within Character John that sets ``Character.spouseto a randomCharacteron the list (let's call itSally), will it just be a reference or will I have an entire instance of Sallystored inside ofJohn`?
For the record, I do NOT want this to happen. I want the spouse property to merely be a pointer to another Character on the list, so that when I need to read the spouse property I am sent to the proper Character and can modify it as needed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Gatekipr.Town
{
[SerializeField]
public class Character
{
public string name;
public Race race;
public List<Trait> traits;
public int age;
public bool isMarried;
public Character spouse;
public bool isPregnant;
public int daysPregnant;
public string job;
}
}
-# I promise there's nothing weird going on in this program despite the odd variable names
It's a reference
Classes are reference types
If you want a value type where it makes a copy you would use a struct
BTW [SerializeField] doesn't do anything here
You probably want [Serializable]
You see, that's what I thought! But [Serializable] was giving me an error
this is my first time testing visual scripting..
and seems last add explosion force part dosent works
anyone could tell me why? thanks
you don't have system included.. so you'll need System.Serializable
heres pic
Also, I've been told this should be a ScriptableObject instead of a POCO. I'll be honest, I'm still a beginner and I don't think I fully get the pros and cons of SOs. What would turning this into an SO bring to the table?
SO would let you define instances of characters as assets and would be very editor friendly, letting you drag them as references to other objects. Right now, how do you plan to define instances of a character? Like lets say you wanted to create John and Sally
Also you can have both a SO and poco here. The scriptable object could just be
public class CharacterSO : ScriptableObject
{
public Character character;
}
which in some cases make more sense. Not sure if you'd want to do that here
Oh that's a really smart idea wtf!
At this point I would probably create them in the editor itself and save them in my disc. I do want to implement a simple character builder in the future
how can i wait until the try get player object value is not null and then return the gotten value?
public static NetworkObject GetPlayerNetworkObject(PlayerRef player)
{
if (instance.runner.TryGetPlayerObject(player, out NetworkObject networkObject))
{
return networkObject;
}
return null;
}
IEnumerator GetPlayerNetworkObject(PlayerRef player){
yield return new WaitUntil(() => instance.runner.TryGetPlayerObject(player, out NetworkObject networkObject));
yield return networkObject;
}
The only thing to really remember about doing the above is your SO asset is just one instance. Everything reference the asset, or character will be reading the same data.
have the GetPlayerNetworkObject coroutine invoke an event, or call some other function to pass the reference somewhere
The question was more of how do you plan to "create them in the editor itself and save them in my disc" without scriptable objects? your alternative would be using monobehaviours. This would be saving them in a prefab or in scene. I mean overall you can get the same result, but one major downside would be version control. Changing a scriptable object asset compared to a scene or prefab is way more clear in git
hm k
Ohhhh!
Yeah, I am already planning on having a monobehaviour CharacterList which will simply hold a list of Characters
Another downside if you weren't using SO here, you wouldn't have a clean way to reference a specific character. For the spouse thing above, you'd have to change that to CharacterSO spouse;.
Could anyone tell me the best SQLite library that supports Windows and Android cross-platform, and that doesn't require using POCO models, being more flexible? I found some here, but they require using POCO models, and I think it's unfeasible considering the number of fields, just filling up the code.
Question, how recomendable is to follow the tutorials in the Learn part of Unity Hub?
XY problem? Why would you need it?
Generally it's not a good idea to resort to using databases when you implement data persistence
I want my game to have offline and online options. If the player chooses online, it uses the MySQL system. If it is offline, it uses the SQLite system.
I could have just saved it in JSON, but I think it's safer to use a local database. I'll encrypt it and digitally sign it.
I don't understand how online mode uses MySQL
Are you saying the client instantiates a direct connection to your server database?
Yes
I really don't think that's a good idea in terms of security
Just use json 🪄 , people will find ways around this very easily especially for offline mode
There is absolutely no control on what comes in or goes out of the database this way
In the future, I will mediate with a REST API
I would suggest you do it the right way to begin with instead of having to worry about refactoring it
Consider something else like bebop or protobuf. And why bother signing an local save file?
You can still implement an online/offline system, but consider implementing a REST API layer from the very beginning and use a local cache or storage using encrypted files in offline mode
Just remember, it doesn't matter how much security you put in. If something exists on the local client it can always be decrypted
dw guys its safe to ship private keys in your client!!! /s
So I don't know the context of your game or what is being saved but just know that clients are perfectly able to maliciously modify the contents
I didn't consider it. In my mind, a local file is less secure than data in the local database.
Encryption and obfuscation is just a temporary solution in those cases
I don't know if it's really safer.
its not safer
doesnt even matter if you decrypt it, someone could mod the game and just ... not use the save file system. manually plug in all the values you want
Also if the offline and online mode are the same profile, that alone will be another issue.
Online mode can be safe, offline cant
At least online mode can be validated, but it also kind of depends on what you are doing
A client can just send their score to you and you can accept what they send, or you can implement an actual system where they might have to submit a demo to the API
So, can I go with JSON, with security measures, or go with SQLite, with the REST API?
what no
Which is better?
unless you want to send sql cmds direct to your server db (you shouldn't) there is no reason to use sql on both ends
sqlite is good for some games so it could be worth using but you seem to miss understand some things
me saying json was just for simplicity because of the existing libraries. If you want absolute online security, your server would be the one calculating and storing all the results by itself. not reading what the client says its result is
What is your game anyway? Is the data important to be valid and not generated by the client maliciously?
It would store the positions of game objects, player data, creature data, and such.
And online, there would be the addition of email and password, which is already a critical situation, right?
Well, yeah
How would you prevent a client from extracting the connection string to your database and fetch all the emails and passwords?
Again, your game's obfuscation and encryption are not going to prevent that, just delay it
Initially, I planned to just test until everything worked. And then, implement the REST API.
you would never actually store what the actual password is. but yea you should specify what you're actually doing here or what online mode is. Is it just a leaderboard, or being able to go into other peoples world?
HTTP is fine for non realtime games but otherwise you need UDP
Especially .NET REST APIs are incredibly simple now that the minimal API pattern exists, I would just write a very minimal API as a middle ware if I were you
Or like rob says, sockets. These should still relay to a server socket that handles the database though
With other people in the world.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
4 lines of code give an api with an endpoint
Throw EntityFramework in there and you have a database connection with maybe 10 more
So I use this API in MySQL?
Sure, or something like PostgreSQL
You can also use SQLite
EntityFramework is highly configurable
Thanks. What about connecting Unity to SQLite? I only found libraries that needed POCO models.
EntityFramework also supports .NET Standard 2.0 which is what Unity supports
I should mention this is EntityFramework Core, not EF6. EF6 might also work but this was targetted for .NET Framework which should be avoided for new projects
Other than that idk how Unity would react when it comes to this. I generally never used databases with Unity directly because of the previously mentioned security risks
And saving should probably be done using binary serialization to files, not databases. Also because the client usually needs some sort of runtime or local DB for these things
Oh, so it's better to save to a local file?
It's what games do
sqlite is a library so you want to find a c# wrapper for it.
Sqlite stores a database in a file and you can interact with its data with sql
Check a random game and it likely does binary serialization to a file in your app data or in the game's folders
Sorry if I say disjointed things. I don't speak English.
Oh
I understood
Okay, thanks guys.
to clarify, sqlite is a c lib hence needing a c# wrapper to make using it easier. It also means depending on how its compiled it wont be compatible with other platforms without a recompile of the c lib.
Thx
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Hey! Quick question here. I'm having a small hiccup with my game. It's supposed to be a sort of Rimworld copy I'm working on, basically a 2d game. The way I try to handle UI and input scenarios is to have a GameStateManager which allows me to track throughout the code what to do and show, etc. I'm trying to implement a PlaceBuildingMode, which should highlight each Tile with a bit of a white effect. It works by having a OnMouseEnter() check if the gameMode is PlaceBuildingMode, and highlight itself. Same thing for OnMouseExit by turning it off. My problem is that I can't find a way to turn the last tile off when switching mode this way.
Iterating over every single tile would be a hassle, and asking each tile to check if it's not PlaceBuildingMode, then turn the highlight off seems kinda bad on performance
i think you should group the white blob into 1 mesh and turn it on off via code
So kinda have a floating Square sprite that turns on when I'm in the right mode, hover above the closest square and turn off when changing mode?
yeah
Honestly love that idea thanks for that! I'll try it and see if it works
i thinking about a seperate tilemap, it track the samething you mention above but it just a white square with like 20% oppacity so you will be more optimize when you just turn it on and off
I decided to start again from the basics, I have an issue where for the walk speed when I put the value on 3 it barely moves I have to put it at least 10 to start moving then again if I have my drag of my rigidbody at 5 then I have to increase the speed above 10. how can I fix this?
Oh it's not really a tile map, I just have a grid with a Tile prefab haha
But I understand the logic behind that idea
how do I activate water hdrp
pls i´m hardcore stuck for 5 day
@keen dew i used it myself 🙂
Good for you, but it's still bad advice
unity only have like 2 way of move right? position and velocity am i correct?
no
position moving if too fast cause tunneling, velocity is way more better bc it have tunnel protect if you turn collision detection to continuous
That has nothing to do with AddForce vs setting velocity directly
<@&502884371011731486> compromised account
no I am using addforce cause its a good way to implement realistic and physics-based movement,
so why it's bad? explain it to me
oh okay then
it isn't bad
they just aren't the same thing
setting velocity isn't automatically better, they have different purposes
In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour - use AddForce instead
Do not set the linear velocity of an object every physics step, this will lead to unrealistic physics simulation.
This is directly from the documentation
he just explain it to me 🙂 but thx anyway
i just understand the question is he moving way too slow when using addforce
What's the problem with using larger values? Is there any practical issue with that?
all the shity ass tutorials are to old pls help
everything moves through position
it's just up to whether you do that directly or use something else to manage it, for example an rb
this one new thx you
you need to formulate an actual question because what you've said doesn't make a lot of sense. also this is a code channel.
@tired summit it's working thanks!
glad to help
sry I need help I dont mange to activate the water hrdp
wth is that supposed to mean
What do you mean "activate the water"
in the unity tutorial they say I need to activate a water in the projekt setings
but i dont have a hdrp in my projekt settings
Did you actually install HDRP
how do I check
hdr is not a render pipeline
then don't answer if you are just going to guess
thks
unity have 2 render pipeline right?
three
what the third one
that depends on what you think the first two are
there are literally three listed there
Fixed it !
That's exactly the same as just using a larger value directly
yeah, i remember the other render pipeline wrong :(((
and it's also really just a bandaid fix and doesn't address what was likely causing the issue (drag + friction)
i think he should explain what he trying to achived first
well my issue was that even if I put the walk speed to 5 my player barely moves even tho I haven't messed with the drag yet.
Why is that an issue?
maybe the force you add just way too small so the friction just cancel it out, but when you put it too high it stack so much object become the flash
there’s no inherent problem with using large values idk I just don't like it lol id rather use low values for movement.
physic doesnt care you like it or not :DDD
Will it not cause any problems though? just curious.
consider whether it actually makes sense
if it doesn't, then changing values might not work as you expect
doubling the speed might not actually double the speed
etc
.Length
what do you mean "x and y"
anyways this is easily googlable
thx
but like chris said, this is easily googleable and that should be the first resort when seeking information.
yeah, i search but it give me weird result so i ask
and idont know .getlength() exist
how would you get a weird result from such a simple question
idk, that why i hop here
you must not have been searching very well. literally the first result searching "c# 2d array length" gives you the correct answer
sounds like you need to practice how to google then
what did you google?
ok... so literally all the results there would give you the answer
this is highlighted in the second result
next time you should consider clicking some of the search results instead of ignoring them
aye aye sir
sry me again i tryed everything I watvhed 5 tutotials and ask chatgpt but the Urp wont deaktivate
you need to remove URP and install HDRP if you want to be using hdrp. also this is still not a code issue
ok sry
where should I ask
Hey, I would like some feed back of my script I just added camera relative movement and I was wanting to know if I did it right but it works though. Also any improvement's I can make.
- If you're assigning the Rigidbody in Start, it shouldn't be serialized in the inspector, or vice versa.
- On line 65 I don't think you should normalizeMoveDirection again there. That means joysticks for example won't let you move faster or slower base don how far you tilt them. If anything you should use ClampMagnitude, e.g.
moveDirection = Vector3.ClampMagnitude(moveDirection, 1);
Like this? rb.AddForce(walkSpeed * Vector3.ClampMagnitude(moveDirection, 1f), ForceMode.Force);
sure
I would encourage the use of intermediate variables as better programming practice, but sure.
Would this do?
Vector3 clampedDirection = Vector3.ClampMagnitude(moveDirection, 1f);
Vector3 forceToApply = clampedDirection * WalkSpeed;
rb.AddForce(forceToApply, ForceMode.Force);
yep
Thanks for the help ❤️
Just Doing the unity roll a ball tutorial but it looks like my navmesh in the empty enemy object isnt lining up with the cube child object, can anyone help?
Press Z
make sure this says Pivot, not Center
ahhh thank you very much
Hey! I made a full body first person controller by watching a tutorial. Walking/strafing left-right doesn't cause any issues, but when I walk or strafe (?) forward or backward, my camera behaves weirdly. I've attached a video. What might be the issue?
This is my player controller script: https://pastes.dev/OHxU8FYs0J
_xRotation -= Mouse_Y * MouseSensitivity * Time.smoothDeltaTime; and Mouse_X * MouseSensitivity * Time.smoothDeltaTime you should never multiply deltaTime into the mouse input
it's already framerate independent
hi, in my game, im trying to rotate a robot based on where it is on the grid its moving. however currently, when its moving left, its rotated downwards for some reason. why is this? (btw it is correctly debugging "MOVING LEFT!!")
here is my code
https://pastes.dev/4Skq4RvoGe
transform.Rotate(0, 180, 0) means "rotate 180 degrees on the y axis from your current rotation"
It doesn't mean "look to the left"
if you want it to look to the left that would be transform.rotation = Quaternion.Euler(0, 180, 0);
and: transform.Rotate(new Vector3.zero); does absolutely nothing
it mean "rotate by 0 degrees", aka - do nothing
that should be transform.rotation = Quaternion.Euler(0, 0, 0) or just transform.rotation = Quaternion.identity;
the other issue you may have here is that we don't know which way your sprite faces in a neutral pose.
you should laso make sure you actually intend to rotate on the y axis here. It's more typical in 2D to rotate on the Z axis only
ohh okay i see, thank you so much for your clear explaination!
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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://www.youtube.com/watch?v=LwOR1_UrGwk
Hey! I'm watching this video to make a player controller, and in the animation section the creator uses a animation from Unity's starter pack with a Unity character. However, I have an avatar that I downloaded from Mixamo (rigged from T-Pose animation). When I try to use my avatar on the starter pack animation, I get this error:
Realistic Jumping System (& B-Hop) With Unity New Input System and Full Body FPS Controller
Project Link: https://github.com/JARVIS843/Unity-Tutorial
(English Subtitle In Progress)
If you have any question, post it in Comment Section
⏲️Time Stamps
DEMO 0:00
Project Setup: 0:16
Fix Camera Stutter 0:26
Download Animations 1:42
Rig + Setup An...
What am I supposed to do?
Am I supposed to retarget it?
is this even unity related?
its c# isn't it? but i don't think its unity related
this is a unity server, maybe ask in the c# server instead
Here you go !cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Does Unity like it when you get components of another object in the start function? I added a gameobject playerGameObject in the inspector and am trying to use playerGameObject.getComponent<MyScript>(); in Start(), but it doesn't appear to actually be getting the component when I start the game.
Specifically I am trying to get the component PlayerMovement which is a script of mine in Start but it stays empty when the game starts even though I confirmed the component is there in the object
actually, as you can see I've been working around it by declaring the transform of the object publically and adding it in the inspector but I thought I should be able to get these in the code too...
There's no problem with that but it's also pointless to do it that way
just assign the object to the PlayerMovement slot directly and remove the playerGameObject field entirely
The same way you did with the Rigidbody and Transform fields
saves time 😂 I don't like the idea of having to drag the same gameobject into multiple fields every time I set up a scene, i'd rather let the code handle that if possible
there's no reason to have all these references to different components on the same GameObject tbh
It's a code smell
Anyway if all these other references worked and this one didn't - the simple answer is that the script is not on that object
Despite what you said
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
ah sorry
If possible the full script
oh oof
uh yeah
A tool for sharing your source code with the world!
I declare the variable in line 14 and assign it in line 46
Get an error in line 80 because it never actually gets the object I'm referencing.
Yep I see that - I notice this is a prefab
are you assigning the prefab
Or the object in the scene?
I'm dragging the object in from the scene
And the object that has the ThirdPersonCam script on it
Is that a prefab or in the scene?
Ok and one last question. If you change:
public PlayerMovement playerMovement;```
To:
```cs
private PlayerMovement playerMovement;```
Do you get any compile errors?
compiles fine
Getting any errors in console when you run the game?
If you got an error on line 45 that would cause the rest of the method not to run, for example
I get an error in game on line 80 when it references playerMovement
Object reference not set to an instance of an object
but nothing else? If you scroll all the way to the top of the console window?
Oh, I missed this one
GetComponent requires that the requested component 'PlayerInputActions' derives from MonoBehaviour or Component or is an interface.
or turn on Collapse to collapse all the NREs
yep there's your problem
that error means the rest of Start doesn't run
And yeah that error makes sense
you can't call GetComponent on what I assume is your generated C# class from the input system.
Yep
That line should just be:
playerControls = new();
// and probably this too:
playerControls.Enable();```
Or actually
I don't understand what you're doing with that variable
since you're trying to get it from the player object somehow/for some reason
and it seems unused
so probably just delete that line
(line 45, and line 13)
damn yeah it's completely unnecessary
ah man the answer is always the simplest one
well now I know that I can't just grab that component off another gameobject
I appreciate the help man you're very knowledgeable about this
Well.. it's not a component so yeah
hmm yeah I suppose not. Hadn't really thought of that. So far I've only used scripts as components but hadn't considered the way you use the input system doesn't actually assign it as one
The new input system is... different.
Component is a very special type of C# object that you can attach to a GameObject
literally every other kind of C# object is NOT a Component
If you just make a class that doesn't derive from MonoBehaviour, that's a regular C# object, and not a Component
that's the kind of object the generated class from the input action asset is
Just a regular C# object.
just out of curiosity, and let me know if this is too broad to really answer...
but are there other cases where having a non-monobehavior script is useful?
Too many to list
this is my first time encountering one tbh
haha figured but fair enough
literally any time you need a container for data or behavior that isn't a Component attached to a GameObject
that actually answers my question thanks
One common example you will encounter a lot in Unity is if and when you get to making your game able to save and load
you will need a container object to hold all your save data that you can serialzie and deserialize
you will generally do that by making regular C# classes and structs.
got it
As someone who learned programming first then got into Game Dev, it's fun to see this perspective, because MonoBehaviour is a very special Unity thing and the vast majority of C# has nothing to do with them.
So... outside of Unity, everything in the universe is not a MonoBehaviour.
yeah I've learned the very basics of a few programming languages but never got past the basic math and printing functionality. only deeper dives I've done were learning a few javascript and powershell libraries.
I've heard people say game programming isn't "real" programming. I mean they're wrong but I get it cause it's a lot different to what I'm used to
Game programming is about some of the realest real programming there is. I'm saying this as someone with over a decade of professional "real programming" experience that has nothing to do with game dev
Game programming is arguably harder in my opinion you have to worry about doing the right thing inside the engine and inside of your code
You have very tight performance constraints in games. You have to do your work within 16ms per frame or less for higher framerates.
In my day job we're happy if we get a response back to the client in less than 100ms
and we don't care as much about it being consistent
yeah my previous experience has been with managing user accounts/data on my old college's website and more recently managing user accounts in windows server.
not nearly as much math involved 😂
the physics stuff and geometry required to pull it off in unity blows my mind honestly. and the shader graph looks pretty insane too. I'm learning it though
yeah those are things a lot of unity guides i watched when i first learned didn't teach me much on i felt like
my first game i created i ended up having to change a lot of things to make it work
mostly with using paths for sprites
first games are usually test runs.. esp if ur learning
Lots of people learn Unity without learning how to really write C# first, and I think that's a mistake.
i mean first developed game for publishing
those too
i definitely did lol
but after a long enough time i learned them both
I mean I gues everyone has their own learning path
but it's clear you're missing out on a lot without knowing C#
oh yeah for sure
same here.. after long enuff and wanting to implement enough mechanics u eventually have a eureka moment
now i use C# for more than just game dev tho after only learning it for game dev
yeah definitely
I just say to myself: "It was a learning experience and that's why it took me and 2 of my friends 8 months for a simple cube runner"
lol yeah that's how it goes a lot of the time
But ye now I am working on my second project and things have been going much faster in comparison
why else would i have 20 projects that all lead up to my most recent one
my first game i had to change so much did it able to be built and ran because i was using editor namespaces sigh
rookie move
mostly AssetDataBase.GetAssetPath
compression got me
how long u been in the industry
self taught, been learning for 5 yrs now
also self taught i began at 14 im 17 now
finally getting into shaders
i've decided not to venture into that area yet lol
i had to get good at blender also
i'm pretty sure i've been receiving help from you for over 2-3 years 😭
shaders + blender is the way to get the coolest effects
Self taught here and doing game game dev for about 2 years now (unity -> unreal -> custom game engine -> unreal -> unity)
i don't as much now that i don't suck but still
id love to get into blender more tbh
<insert shia "Do It!" gif>
I tried once, deemed myself incapable and decided I'll do it later
i plan on just doing the same as how i learned html/photoshop/unity/c#
just gonna copy stuff over and over.. venture into my own things.. and finally hopefully it clicks and i can make anything i think of
#1253440741322133545 message i made my first one the other day
gotta start somewhere tho 🙂
https://dotnet.microsoft.com/en-us/learn/csharp i still need to do some of thsee as well.. just to see how i fair w/o having Unity as a crutch
if i dont want my game data got tampered, is putting them on server the only way to do that?
yes but if its a single player game, you really shouldnt worry
I Need help from someone who has time im tryna Programm my own Game with Unity
If you want help here you actually need a specific question
If you want to collaborate then !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
so i need to type !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Please just read the bot message
Guys i need help creating a combo system in unity 3d can anyone help me with it i need help with coding
which coding
to run the combo animations
I have created 3 combos but they are not runing as i want
i need to hold mouse button to make them work i tried checking diffrent things but it is not working
would help if you shared the code / setup
ok whould i msg u in personal?
if (timer > timeLimit)
{
fSpeed *= 3;
}
if (timer > flametime)
{
flame1.SetActive(true);
}
if (timer > flametime2)
{
flame1.SetActive(false);
flame2.SetActive(true);
}
}
is this an effective way to make sprites change?
what it does is make rockets shoot out like that
I can't understand what you want to do from this code. I suspect others don't either
i kinda didn't understand actually waht u did here
Actually i had made three combo ounches i need a script so that i make play 3 combos one after another but something is wrong like when i click my mouse once my player does 1st attack but i need to keep presing my button 3-4 times to activate 2nd attack and the third attack don't even play
i want to make it so that the flames change from the rocket after it spawns
maybe make it so that making a click activates a timer which makes the other combos play?
i am trying that but not getting exactly what to do
Can u share a screenshot of your blend tree
Make it so that clicking activates a function which changes a bool value to true, and make it so that if a bool value is true the said timer counts down
Whats a blend tree?
ok i will try
The where u create all animation
Well ill try using that since i never used it before
Not on unity rn tho
then how u created the birds movment and fire?
I posted the script here
It just activates some objects
👋 This is my CameraRoot placement (Main Camera's position gets adjusted to CameraRoot on game start). However, this doesn't give a good result. Where should I place my camera?
I'm sending a video about what I mean now
As you can see in the video, the arms glitch out
looks like a clipping issue
Hello boys, i made a spawner in my game, instantiate a GameObject enemyPrefab on a empty Object called spawnPoint.
Tried to modify the enemyPrefab on the inspector and it doesnt change the enemy.
Made a new Spawner with the new enemyPrefab i want and it still generating the same enemy idk why O.o ill try to resolve by myself but just ask if someone knows what i am missing
How can I exactly fix it?
check your camera inspector
What am I supposed to change in main camera tho
If u got a script u could use void start to set it's coordinates that u want to look in when starting game
does anyone knows why i still getting this problem? if i assign the sprite of my main Character it changes but if i create a new empty object and assign the new Enemy Prefab i want to visualize it doesnt shows, it shows the old Enemy prefab :d
Try reducing the clipping plane
i should note, that you cant set it lower than that value, once you enter and exit playmode, it will default back to 0.01
I encountered it before
i think the unity devs forgot to add a [Min(0.01f)] attribute to the field. Which there really should be to make it clear that you cant go lower than it
How to type the two lines? like what combination should i use on my keyboard
depends on your keyboard layout. that is called a pipe character or vertical bar, look it up with your keyboard layout
depends on your keyboard. on most typical english ones, it'll be shift+backslash
either above or beside the enter key
it displays an error for me
could they be the wrong symbols
Heres the tutorials code
start by configuring your !IDE if you aren't seeing errors underlined in your code
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Oh
ill get VS Code then
was using sublime since i was using html on it a while ago
you still need to actually configure vs code.
wym configure it
That mostly turned out to work fine but I still have some issues. For example when I jump, the camera goes in the player.
I have done this before in the past with making a full body fps controller. Simplest way to fix this would be to have different camera positions. Like when crouching you would have an empty game object for the camera to move in this position when crouching.
Well in my case I did that for walking, running , jumping , and crouching and it turned out to be good
Should I determine when should I switch main camera's position with animation events?
Sorry I never used animation events so I wouldn't know in your case . all I did was move the camera to a new position depending on how I was moving.
But if you did move the camera as soon as the crouching played, wouldn't it be laggy?
no it would not be laggy unless your doing something wrong.
also you should hide the mesh of your players head so you have a better camera position and it won't clip into it
but turn on the shadows for the head
How is that exactly done?
So as soon as crouch key is pressed I just move the CameraRoot to a bit lower of its original position?
yes
ur gameobject names give me anxiety
I got a Mixamo rig though, the mesh only seems to be the entire character, the Head in hierarchy is only a transform
What I did was go into blender and seperate the head mesh
My camera follows the animation though which is what I mostly want since I want head bobbing in animations
Let me try that
i also have one of those as a child object
How do I change this script to work between touchscreen and mouse controls?
Yooo I have an issue, I want to respawn the player but the game does not recognizes it, but for some reason it recognizes when the console has a message
Unity's new input system should work if that's what you're asking
we're gonna need much more detail than that
Funny thing is I sometimes get confused what I am looking at when looking at the names lol.
{
public GameObject player1; //this is a prefab of the player
public Transform respawnPoint; // this is a empty game object I have
void Start()
{
player1 = PlayerStorage.P1Prefab; //this is the storage that has the prefab the player choosed
}
public void RespawnPlayer1()
{
Debug.Log("wazaaa"); //THIS WORKS
player1.transform.position = respawnPoint.position; //THIS DOESN'T
}
public void YouDiedBitch()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Debug.Log("WompWomp");
}
}
I'm using that, but how do I change the input based on the device?
ur names be like: S̸͑̕p̸͆̐a̴͋̓w̸̓́n̸̈́̀Ć̸͐a̸͐m̿̓p̴̐̕P̴̿͝l̸̐̾a̴͋̓y̴̔͒e̴͌r
void Start()
{
respawnScript = GameObject.FindWithTag("RespawnScript").GetComponent<RespawnThing>();
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.transform.CompareTag("PlayerP1"))
{
if (P1move.isFlying == true)
{
P1move.isFlying = false;
}
if (P2destroyer.onePlayer == false | P2destroyer.twoPlayers == true)
{
respawnScript.RespawnPlayer1; //This works but the FUNCTION in the other script doesn't
}
else
{
respawnScript.YouDiedBitch(); //If there is only one player then it restart the entire screen
}
}
}```
savage method names ||very professional ;)||
also the "YouDiedBitch()" function works
thats y i always keep a design doc/ or just notes handy..
i'll write down my structure and what scripts are paired with wat
it really helps
debug everything
see whats causing the error.. do u even have a console error?
that may help point out the issue
maybe respawn script is null
if it is with me, it doesn't
when the player collides with the enemy nothing happens
So I tried doing that but when I'm trying to select I can only select the bones. I have no idea about modelling to be honest, how can I choose the head part and not just the bones?
It is!!
like I said, the Debug.Log message works
when the player collides with the enemy the message appears
How to separate meshes with the shortcut P and use the selection, material/shader, or loose parts as the criteria for splitting.
sorry.. ur code formatting is bad :P !code use tripple ticks for blocks like that```
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
oh okok
Discord didn't let me send the hole code (fuck nitro)
The issue is when I'm trying to select it only picks up the bones, I want to select those black lines (I don't know what they're called)
Dont select the bones when going into edit mode select the mesh itself first then edit mode
yea thats not got a link associated with it.. i do like that paste bin tho.. nice and simple
https://scriptbin.xyz/ ill need to bookmark it along with this one
Use Scriptbin to share your code with others quickly and easily.
I know, I just shared the pastebin website for the guy haha
How can I stop this slippery movement when on the edges?
lol.. ive never seen anything that slippery..
my character slips off of edges when its too close to it.. but not like that
So I choose the mesh instead of the armature in Object Mode, then go into Edit Mode?
I'll already paste it
how do I send that to you? (or so)
Most easiest way is to watch a quick tutorial or go into blender discord!!
My bad, the context changed quickly haha
Will do, thanks!
paste the code into the paste-bin website and hit the Save button
it will generate a new URL
copy and paste that URL to us.. then we can see ur whole code
(formatted properly)
Use Scriptbin to share your code with others quickly and easily.
Thanks to you!!
and which part isnt running? sorry, you said the debug runs but what doesn't?
Oh sorry I forgot to add that
np, just trying to get the full picture
It was my physics material. I kept getting stuck on walls.
oh.. hmm 🤔 i wonder if you'd need to add slippery materials to the walls themselvs..
but not the ground..
that'd suck
I dont use Rigidbodies that often so I dont run into issues like this that often sorry
u might could use two different colliders on ur player.. (one for the feet that have friction) and one for the body that doesn't
but not sure how that setup would look
player1.transform.position = respawnPoint.position; ur trying to assign the prefab to that position
not the actual instance/clone of the prefab u spawned..
thats ur problem
Use Scriptbin to share your code with others quickly and easily.
Ohhhhh
damn
I mean
in the inspector it appears the "Clone" thing
and use that reference instead
give me a sec
yea.. but ur using the prefab version u assigned in ur script
not the actual clone that u spawn
Instantiate returns a copy of what it spawns
its pretty simple to cache it..
thers another example or so on ther.. or u can just google how to cache a gameobject u instantiate
or maybe u need to cache a script instead.. u can do that too with casting thats (i think thats) what ^ that example is
now it shows me this error
right, that would mean you wrote something incorrectly
whats line 47 of damagehitbox
the cast is unnecessary as most people will be using the generic Instantiate method rather than the old one that returns Object (which is what this example is using)
lol i knew u were typing in response to me 😅
respawnScript.RespawnPlayer1;
this is not a valid line of code
yea.. not sure theres another doc page
yeah this is an old version of docs
its the line 25 and 45
but i usually dnt do any of tha () stuff
thankyou 💪
(just changing the version slug)
(this one)
ahh okay
ok, so that means you mention RespawnPlayer1 of respawnScript
but you don't actually do anything with it
Oh bruhhhh
brick wall hit ya?
I forgot the ()
hehe.. classic
I'll try this code.. Thank you so much!!!
#💻┃code-beginner message use this instead
i accidently posted a legacy doc page
(older unity version)
u can just set it directly
thats what boxfriend was correcting
u can use it as a gameobject or any other component u need
might save u a .GetComponent to just use the component (up to what ur doing overall.. i didn't read too much of the code)
I'm actually new at this, didn't now how to code so yeah I'll try that 😭
but how can I get the transform from the clone?
GameObject myClone = Instantiate(...
then..
myClone.transform.position;
same way u get teh transform from anything
its because I also have a Spawner
idk if use that script instead
do u want me to show u the script?
I started like 1 month, I wanted to make a super fast game
this is literally the last step
😭
1 sec i gotta hop in a vc real quickbrb
using System.Collections.Generic;
using UnityEngine;
public class PlayerSpawner : MonoBehaviour
{
public bool P1;
void Start()
{
if (P1 == true)
{
Instantiate(PlayerStorage.P1Prefab, transform.position, transform.rotation);
}
}
}```
np
u dont even have a variable declared for this.. 🤔
the storage is just this XDDD
public static class PlayerStorage
{
public static GameObject P1Prefab;
}```
then in the character selector I have another script that changes the P1Prefab for the character you've choosed
ooooh
since its a gameobject u should be able to go..
GameObject spawnedGO;
if(P1 == true)
{
spawnedGO = Instantiate(PlayerStorage.P1Prefab, transform.position, transform.rotation);
}``` right?
then spawnedGO.transform.position anywhere u need after its been assigned
check the console I guess
It didn't work 😭
void Start()
{
if (P1 == true)
{
spawnedGo = Instantiate(PlayerStorage.P1Prefab, transform.position, transform.rotation);
}```
this is the Spawner
{
public Transform respawnPoint; // this is a empty game object I have
public void RespawnPlayer1()
{
Debug.Log("wazaaa"); //THIS WORKS
PlayerSpawner.spawnedGo.transform.position = respawnPoint.position; //THIS DOESN'T
}```
i dont think u'd put static on the spawnedGO variable..
this is the respawn
Oh, I though that I needed to put that
this means a gameobject has a component attached to it that had been moved or deleted.. and makes it have a missing reference
Does anyone know a video i can use to learn the basics of C# 2D?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
lol
hmm quick question. I am applying a force to my player rigidbody and noticed the results are inconsistent at different frame rates. Is this expected behavior?
where are you applying it
// Apply Additional gravity to player when falling if (state == MovementState.falling) { rb.AddForce(transform.up * fallSpeed, ForceMode.Acceleration); }
fall speed is a negative number I apply to the player when they're falling so that they fall faster
this does not tell me where you are applying it
one sec
what do you mean by where I am applying it? To what object or where in the code?
update is frame dependent
thats bad
where-as fixed update happens a consistent amount of times
ideally you wanna do anything physics related in fixedupdate for this reason
(and for the opposite reason anything input related in update or via events using the "new" input system)
hmm well now i'm not sure the way i've implemented this is right
Farming System
i dont wanna block the whole channel, this is a relatively complicated system , needs to be explained in detail, so i gonna thread it
its a pure coding question
Yeah I'm going to try a different way. I think even if I used fixed update, applying a force every frame is a bad idea.
the fall speed is a negative number so it is applying an increasing downward force but I think it would still be inconsistent on fixed update unless I'm misunderstanding how it works.
FixedUpdate is consistent. That's its thing . . .
hmmm fair enough
it works
applying multiple forces like this feels unholy
but it is the result i wanted thanks yall
Is there a way to add the red/green/blue axes moving arrow gizmos to an in game level editor? Basically, is there an easy way to make a gizmo for moving an object along an axis in a game like the one in the unity editor itself, or would i have to make that from scratch?
relativly new to unity and im trying to hunt down the source of some camera jitter. im using lerp, ive got my rigidbody movement in fixed update, camera in late update and my logic in update. It is specicly things in the world that do this, I have a test object parented to the player and that has no jitter on it.
void LateUpdate()
{
camRotate.y += Input.GetAxis("Mouse X") * SenseX;
camRotate.x = Mathf.Clamp((Input.GetAxis("Mouse Y") * -SenseY) + camRotate.x,minY,maxY);
cam.localEulerAngles = Vector3.Lerp(cam.localEulerAngles, camRotate, camSpeed);}
The reason is you’re using lerp wrong
Last parameter (t) is supposed to be a percentage, but you’re passing speed instead
You can replace Lerp with MoveTowards if you want and it’ll work
my camspeed is a float of .4f
Yes, it’s not a percentage
obligatory: use cinemachine
I'm super against that ^
let me guess, you're one of those "if you didn't make it yourself then it isn't worth using" kind of people? because cinemachine is great and will be absolutely miles better than anything anyone asking questions here can write
and there is no need to reinvent the wheel when there is a perfectly good wheel sitting in the garage
the correct code for what you want involves Quaternion.RotateTowards(cam.rotation, targetRotation, camSpeedInAnglesPerSecond * Time.deltaTime);
no, I'm one of those "Cinemachine is bad for gameplay" kind of people.
in what way is it bad
Does your Rigidbody have interpolation enabled?
Does the player object also rotate ever? If so how?
I have to go in like 2 minutes so can't explain my experience now 😛 however just try using it as gameplay camera in like a game jam and you'll see.
i always use cinemachine and it's great
interpolation is not enabled and the player object was set up to rotate but then I changed how the camera works and am going to need to make the character follow it at a later point but it will.
You need to enable interpolation
Just switch to this for starters: cam.localEulerAngles = Vector3.MoveTowards(cam.localEulerAngles, camRotate, camSpeed);
And you need to make sure nothing in your code is breaking the interpolation
however it'll also be wrong
Needs deltaTime
interpolation fixed it, using movetowards mostly worked until it made it spin REALLY fast but the lerp seems to work even if not the intended way
That part is probably from using Euler Angles instead of Quaternions
How would i lock the FPS of my game? and how would i do a 3f delay before an input
i want it to be 60fps and 3f jumpsquat
fixedupdate happens a certain number of times per second reguardless of framerate and I believe it is 60 but I could be incorrect
fixedupdate is 50 times a second so that wouldnt be that method
is there a way to change fixedupdate to 60?
sure, but you can also just target 60fps for the entire application https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Application-targetFrameRate.html
that won't change the rate of fixedupdate (which increasing the rate of which can impact performance)
so wait how often does VoidUpdate trigger?
update is once a frame
Update is called every frame by the engine
so yeah if i lock my fps to 60 then that gives what i want
and how do i add a 3f delay to something?
is there a reason you want to lock it to 60fps?
i want you to hit jump, 3frames go by, then you jump
google "update timer" or use a coroutine
fighting game, i need to be able to mess with frame data and stuff
and i want 3f jump squat for any inputs that end in an up to be possible raw
does this mean its already locked to 60fps?
no, that is for Timeline
wheres frame rate in project settings?
oh, google said it was
So what script should i put the fps in?
cause right now my only script is the player movement
I believe you can have one that is just the scene in general that is where I would put that and the match timer etc
so you would create an empty game object and attach the script to that
yes
cool
and looking at the documentation you also need to disable vSync for it to take effect
Pls guys am new to unity and I have a problem now look at the first one and the second one I can't find assets again pls why
should do just test it
how do i test it?
don't crosspost. and i already answered you
#💻┃unity-talk message
or do you just mean see if it gives an error or not
Also i want to detect a dash input by either a single button, or by hitting AA or DD in quick sucsession, how would i do that?
might not be the best way to do it but you could keep a timer for how long it has been sense the last of the same input and if its close enough it would run a dash function that could also be called at the seperate button press
hm alright
i should probably find a good way to do it since i also want to be able to detect if its like down, then forward for quarter circle inputs, or down, forward, up, ect
so in update you add a simple int that increments every frame, whenever you press A or D it checks the number of frames sense the last one, check if its the same one, if its all right you run dash, and then if it does it or not set the timer to 0
true
so just one timer to see frames since last input
then like check what the last input was, and how many frames ago?
would that work for like a 268 input since that would need 3 inputs?
or if you want one system that can also do every motion input you have a custom struct that stores what frame it was and what the input was then just store an array of these
so basicly you have an "object" that contains "Input" and "Frame"
i might go for that, so its easier for future me
then you can check the last x to see what the inputs are
i just like dont want to overthink it and make a way to complicated system i dont need, but also dont want to make it bad and have to redo it
you could also just have it be 2 ints and have the numpad notation and then give each button a number
does an image or anything that has a canvas as its file holder must be within the canvas range?
but it might be bad to overthink it cause i know i want super cancels so you can do like 623 then 236 and it would cause you to cancel a dp into a 236236 super
but that might be a little complicated for my skills
yeah i do plan to code directions in numpad just cause thats easy and makes sense
i wouldnt worry about doing advanced combos or inputs just make a game figure it out one step at a time
yeah true
i got basic left right and a jump right now
and im gonna figure out 66/44/macro dash/airdash tommorow
and also the jumpsquat thing
instant airdashing works because they dont check for 1, 3,7,9 it just sees an input that is 8+6 then a 6
interesting
good to know
i might also figure out normals/links/gatlings before worrying about specials
my first big goal is to make sol badguy though
(and by that i mean just a shoto probably)
i mean sol isnt even really a shoto he is more of a rushdown
Yup. I just set a static Config/Settings class somewhere with this code:
[RuntimeInitializeOnLoadMethod]
static void Init() {
Application.targetFrameRate = 60;
// other static configs I want in my program
}
Much cleaner than ahving it on a MonoBehaviour imo, and can prove useful for more usecases.
just keep in mind that a LOT of fighting games features come from useful bugs in old arcade fighting games, these are shockingly complex systems to do "correctly"
yeah
Unity will parse ALL static methods with the RuntimeInitializeOnLoadMethodAttribute and execute them on load, so any class will do.
fighting game is prob a hard kind of game for your first decent sized project
i also need to figure out how to make movement not feel so floaty and awkward
are you using rigidbody or kinematic character controls
fighting game is one of the easy options imo lol.
rigidbody cause thats what i remembered how to do
like street fighter not smash
you can easily get your foot hurt by going with something like RPG or Platformer. Design is hard.
so motion inputs
yeah it's all about asset requirements imo.
or i just have all my characters be charge characters because that sounds easier to code 👍
Code will be done eventually.
rigidbody isnt what you would want to use for something like that to get it a lot tighter even the most simple kinematic controllers will be much snappier
whats the difference?
Kinematic you add in the like gravity and everything yourself right?
because instead of using forces that have to cancel out and build up its just binary move left move right
that's Kinematic vs Dynamic (Rigidbody). Making a Fighting game with full Rigidbody impl is on a whole other level
ah sick, ill redo it tommorow then, the rigidbody stuff only took like 30min anyways
ty for the help
very convient that you are familiar with fighting games lmao
I am no means an expert in either unity or fighting games but I do know a little bit of basic game development, messed around with kinematic vs physics and other stuff in godot
rigidbody logic thing actual physics: https://www.youtube.com/shorts/JbiH5Ggjvxk
Rigid body dynamics physics animation in blender 3.4 I will make a tutorial on it comment
thanks for watching
#shorts #ytshorts #blender #3danimation #rigidbody #physics #animation #youtubeshorts #cube #camera #multicamera #shot #shot #simple
you know more than me
and it was nice you could give advice with me not having to explain what motion inputs and numpad notation are
hello beginner here, ive been trying to build a simple scene for android and this error keeps popping up, the only thing in the scene is ive imported the "google cardboard xr" onto the scene, other than that theres nothing in it i have tried most things on google that others have claimed fixxed their issues anyone have a clue on how to fix this?
this is a code channel
bruh is there a help channel
there are beginner c# courses pinned in this channel, start with those. i personally recommend doing the intro to c# course then the junior programmer pathway on the unity learn site
Thanks!
How can I add the gameobject inside pieces gameobject inside my green box (image inside piece slot) using code? I tried to search google about it but I cannot find any script that solve the problem.