#💻┃code-beginner
1 messages · Page 406 of 1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraSwitcher : MonoBehaviour
{
public Camera camera1;
public Camera camera2;
void Start()
{
camera1.enabled = true;
camera2.enabled = false;
}
void Update()
{
//this key is not switching anything
if (Input.GetKeyDown(KeyCode.C))
{
SwitchCams();
}
}
void SwitchCams()
{
camera1.enabled = false;
camera2.enabled = true;
}
}```
But in the end, it depends on your coding style
tbh because you said this 'for example, do i create a script for the cameras and put it in both cameras?'
which clearly demonstrates that you did NOT 'get the code shown'
but i said it as a joke, since my teacher says it most times
because i am new to unity and didn't knew i could simply apply the variable "camera1" to the "Main Camera" with such ease
There's an issue.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraSwitcher : MonoBehaviour
{
public Camera camera1;
public Camera camera2;
void Start()
{
camera1.enabled = true;
camera2.enabled = false;
}
void Update()
{
//this key is not switching anything
if (Input.GetKeyDown(KeyCode.C))
{
SwitchCams();
}
}
void SwitchCams()
{
camera1.enabled = !camera1.enabled;
camera2.enabled = !camera2.enabled;
}
}
Try this
public void LoadData(GameData data)
{
transform.position = data.PlayerPosition.ToVector3();
}
public void SaveData(GameData data)
{
this line --> data.PlayerPosition = new SerializableVector3(this.transform.position);
}
I am getting null reference exception on Save data.
[System.Serializable]
public class GameData
{
// public List<InventoryItem> inventoryItems;
public int PlayerId;
public SerializableVector3 PlayerPosition;
public List<Slot> Container;
public ItemDatabaseObject database;
public GameData(){
// this.inventoryItems = new List<InventoryItem>();
this.PlayerPosition = new SerializableVector3(0,0,0);
}
}
Why is that?
the first script is on my player
it worked
Nice
then data is obviously null
I got a problem that should be trivial:
[SerializeField] private Transform InventoryHolder;
private int maxItems = 24;
//stores items as (name, count)
public Dictionary<string, int> storedItems = new Dictionary<string, int>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//pressing "e" opens the inventory display
if (Input.GetKeyDown(KeyCode.E)) toggleInventory();
}
private void toggleInventory()
{
Debug.Log("pressed E");
InventoryHolder.SetActive(true);
//if(InventoryHolder.GetActive) InventoryHolder.SetActive(false);
//else InventoryHolder.SetActive(true);
}
i assigned an object to the InventoryHolder inside the editor, it is a recttransform with 2 images attached, one also containing a gridLayoutGroup.
However, i get the following error-message:
error CS1061: 'Transform' does not contain a definition for 'SetActive' and no accessible extension method 'SetActive' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)
is there anyone here who could help me with a local hosting issue I have? Im very new to unity and cant figure out why stuff isnt working. I had it all working before I went to sleep, I get back on in the morning, make a few changes to something that shouldnt affect the networking and suddenly clients cant connect 😭 pls help
if i string.split(new string[] {"ab", "a" }) it first tries to split by longer string right?
nvm, chatgpt solved the issue lol
that code makes no sense. you cannot string.split on an array
sorry, my bad. I mis read what you were doing. Yes that should be OK
so it will split by the first string rather than second
at each character it will try to split by each entry in the array in sequence
Starting from the first entry in the array, not the longest, like how a regular loop would iterate through an array
"abcdef".Split(new string[] { "c", "cd" }) yields ["ab", "def"]
Hello community. I have 2 scripts: Progress and ProgressBar. I need to update progress bar without an Update method.
ProgressBar
using UnityEngine.UI;
public class ProgressBar : MonoBehaviour
{
[SerializeField] private float _currentProgress; // Current progress amount
[SerializeField] private Image _barImage;
private float _maxProgress; // Link to Health in Threat class
[SerializeField] private Progress _progress;
private void Start()
{
_currentProgress = _progress.CurrentProgress;
_maxProgress = _progress.MaxProgress;
}
private void OnEnable()
{
_progress.Changed += ChangeProgress;
}
private void OnDisable()
{
_progress.Changed -= ChangeProgress;
}
public void ChangeProgress()
{
float fillAmount = _currentProgress / _maxProgress;
_barImage.fillAmount = fillAmount;
}
}```
Progress
```using System;
using UnityEngine;
public class Progress : MonoBehaviour
{
[SerializeField] private float _maxProgress = 5000;
[SerializeField] private float _currentProgress = 0f;
public float CurrentProgress => _currentProgress;
public float MaxProgress => _maxProgress;
public event Action Changed;
private void Start()
{
}
public void IncreaseProgress()
{
_currentProgress += Global.damage;
Changed?.Invoke();
}
}```
Thx for help 🙏
So give Progress a reference to ProgressBar and call ChangeProgress when required
You have not asked a question here
Is there anything wrong with this?
But I have an event
I want to update progress bar without an Update method.
The fill is made, you just don't pass the new progress value to the bar. You can do that with the event
This looks totally overgineered for something so simple
Yeah agreed, this could just be a progress.ChangeProgress(newValue)
No need for events and cross-references and whatnot
Yes that is your goal. However since you posted here, this probably means that you're having issues with doing this
Describe the issue
Really?
yeah, really, serious overkill
I call the method IncreaseProgress() and want to see ProgressBar is changing. But nothing happens.
Suggest to make one script?
2 scripts is fine just much simpler, get rid of all the unnecessary fluf. Progress shuold reference and call ProgressBar.ChangeProgress and pass in a value
When you do _currentProgress = _progress.CurrentProgress in Start, this copies the value. _currentProgress will not change when _progress.CurrentProgress changes in the future.
Sure, you use an event to catch when the progress changes, but you're not passing the new progress value anywhere, so the value of _currentProgress stays the same.
But yes this can be simplified, it does not need to be that complex for it to work. Keep it simple. No events are required for this to work
So, one or 2 scripts?
Do you mean links between scripts without events?
The issue is the values are changing. But bar not react.
The values are changing in your Progress script, not in ProgressBar.
For the reasons mentioned above
man, it's so simple
public class Progress : MonoBehaviour
{
[SerializeField] private float _maxProgress = 5000;
[SerializeField] private float _currentProgress = 0f;
[SerializeField] private Image _barImage;
public void IncreaseProgress()
{
_currentProgress += Global.damage;
float fillAmount = _currentProgress / _maxProgress;
_barImage.fillAmount = fillAmount;}
}
}
interesting how do you fill barImage?
What do u mean?
Yes
tbh I see little point in there being 2 scrips for this
I have thought the same when began to write here. But... Thank you very much, man) Your scripts are an Occam's Razor
so I got 25 lines of code down to 9
which will actually work
Not beautiful structure x)
Beauty is in the eye of the beholder and I like to make thing beautiful for the compiler
I meant only one SerializeField)
lol
Actually I wanted to make something like MVC pattern. Separate logic and visual.
Then 2 scripts, but no need for all the cross referencing. ProgressBar should know nothing about Progress if you adhere to strict MVC principles
and, this is game dev. My advice, keep all the app patterns where they belong, in app dev
Any way to morph a square into a rectangle without messing up the sides line width? 2D
I am the beginner. So, MVC and other MV patterns are difficult for me.
Don't get me wrong, what you did was not bad as such and in a more complex environment would even have been good. But for a simple situation KISS should be your guide
I have made one megaclass for whole game and now is dividing it x)
that can never be a good way of developing software
Now I know it. A year later, I returned to the project and realized that I did not understand what was written х) And then I bagan to separate megaclass to modules.
About my question? 🥲
I thought using Manager would provide more control. Some tutorials are garbage.
Almost all tutorials are garbage
May be use images with one resolution?
What do you mean one resolution?
I don't see your problem, just change the renderer bounds property
width x height of image
Are you a senior or middle?
in what context?
Programming experience
very, very senior
im having a problem with 3d coding, im following brackeys tutorial to make movement with the camera and i have this code
The error that im getting is weird because i have asigned the player to the variable...
this is the inspector of the camera
GameObject starEffectObject = Instantiate(starEffect, this.transform.position, new Quaternion(-90, 0, 0, 0));
how to make the x rotation to -90?
this code doesnt seems to work
because this new Quaternion(-90, 0, 0, 0)) is nonsense
As I see it, most experienced programmers have a negative attitude towards tutorials.
yes, with good reason, we see the harm they do every day
hey guys.
is there a way for me to calculate a force, that when applied to a rigidbody with a weight of float weight, will have the rigidbody be thrown towards Vector3 target?
i want my AI to calculate this force, to throw its grenade prefab at its target. weight needs to be taken into account to make sure the grenade lands on the target position.
Of course, but you will need to specify a lot more parameters than that
is there i need to change?
its cause the tutorials almost always have terrible code
read the docs on Quaternion, specifically Quaternion.Euler
i probably already have all of them in my scripts.
btw i need to do this with the unity physics system IN 3D SPACE, not curves or whatever
anybody that knows where my issue lies?
Such as how quickly should it go to the target, how high should the top of the arc be? What's the gravity?
All of these are parameters for the calculation.
You want the parametric projectile motion equations
Your screenshot clearly shows it not assigned
(you also have two copies of the script on the object)
Yes it still clearly shows it not assigned
We need seniors on Youtube
this was the problem yes, but i do not understand, brackeys code is looking left and right but if i try that then my player is looking up and down?
if i make a "tutorial series", it sure as hell isn't going to be video-based
Nobody who needs the infomation I could give them would watch a YT video made by someone like me, way too much like hard work
You did something wrong with the setup then
But it's the only way to reach gen Z and A
You are right. Begin to understand it when the project is expanding.
Then that is an education problem which should be resolved not pandered to
anyone who refuses to read an article is probably not going to make it far
But I love pandas
Can't Read? Won't Read? Don't do Dev. Go and get a job at McD's
I guess it depends on whether your goal is engagement or education 😂
Gotta be education above all else
creating educational content (insert scare quotes as needed) solely for engagement is probably what makes so many tutorials so terrible
weird, im doing what he does and its different, my character is looking up and down and his is looking to the left and right, is there something im missing?
Text is better?
Written information, with short videos to provide context or illustration, is superior.
Text + Images, yes
hey man do you mind taking a look in #archived-code-general
stop pinging random people for help
Yes I do mind, I also do not appreciate being pinged
Indeed. As mentioned, you did something different and wrong with the setup
aight mb
The code is only one part
The setup in the scene is also important and must be correct
It's easy to point at popular video tutorials and say they should have better code. And there are definitely many cases where they have bad code for no good reason. But I disagree with the idea that writing bad code as a beginner is "the wrong way" to learn and you should be learning to write code the way experienced seniors do. Those senior programmers didn't learn code that way. They made stupid mistakes, many of them, and learned from them. They understand why it's so important to write "good" code, because they've experienced what bad code does to productivity.
God knows most people would completely ignore it, but a series on "bad code" and its consequences would be very useful
demonstrating how poor design decisions lead directly to bad outcomes
Learning from mistakes is the best way to learn. I don't think you can avoid that part by having someone tell you their experience. It's not going to stick. Did you learn that way?
I think you miss the point of why tutorials are universally bad. They only ever show one way of doing one particular thing, there is no Why or When component which is required for good learning
how about if i add the buttons that i am trying to program to the prefab itself will that work?
That is true. It's very hard to replace experience.
But I suppose you can nudge people out of bad practices.
I see a lot of people referencing every single prefab as a GameObject, because that's what they've always done (or, god help them, that's what they saw in the tutorials)
You know I have never yet seen 1 tutorial on C# and Unity which pointed people to the MS or Unity docs for further reading or explanation of why they have done certain things
Some of tutorials are made for selling courses.
99% are click bait only, copies of copies of bad copies of bad tutorials
It's a rare thing. But so good.
how do I pass an Interface through a method?
Make a parameter of the interface's type
but how do I ensure I pass this.Interface?
i still dont understand sorry
I don't know what you mean
You make a method that takes an IItemContainer as a parameter
and then pass an instance of this
you are trying to construct a Quaternion using Euler angles. You need to use the Quaternion.Euler method
yes
yes
how do I pass this ItemContainer
this
By passing an instance of an IItemContainer as the parameter to CraftingProcessInDUDE
a Quaternion is a four-component number. The components are not Euler angles.
what should I write
CraftingProcessInDUDE(someInstanceOfAnInterface)
idk what euler angles means
You can add 1 to that list. https://youtu.be/XtQMytORBmM?t=1180
This page explains what they mean
Read the documentation.
okay, thanks
The representation of an orientation in the form of Pitch, Yaw, and Roll (A Vector3)
what do you think the -90 is that you used in your code?
an -90 rotation transform
yes, in Euler angles
The four parts of a quaternion are numbers in the[-1..1] range. They are not angles.
new Quaternion(-90, 0, 0, 0);
This is a nonsense value
What should I hide? As I wrote above, I wrote the game in one class. After a while, I couldn't read my own code. After a while, I began to divide it into parts and it became a breath of fresh air.
is there anything here u guys can see that makes my player look up and down instead of left and right? i want the player to turn left and right when i go with my mouse to the left or right side...
well this one is work
this is the view
maybe use transform.Right rather than Vector3.Right
nah, player body is still looking up and down + the camera view isnt even changing
Point your arm to your right.
Imagine rotating yourself around your arm.
The problem will reveal itself (:
sorry, up and down is .right, you want .up for left/right
also unrelated to the issue, but don't multiply mouse input by deltaTime, it is already a delta from the previous frame so doing that multiplication ends up causing stuttery camera controls
i tried that, its still the same...
you tried what?
what vector3 or transform
µ
Since you're using Rotate, you'll want to use Vector3.up anyway: Rotate works in the "self" space by default
However...
if i go left and right he does this.
Your object has been rotated.
Blue is supposed to be the forward axis.
but it's pointing straight up
This is probably because you've imported a model from Blender.
Copy code to chat is better)
i did
I would suggest parenting the player body to an empty object
You can then rotate the model however you want
so i put the model in the empty player object, then i put the empty player object in that variable of the camera called playerBody?
bingo
no matter how weirdly the model is rotated, the parent object is nice and consistent
Hey, me and my friend wants to start a collaboration game but we cant really get it to work. He started the project as a 2D game but when i start up the project it's in 3D, Why is that?
You are using Transform.Rotate, which works in Space.Self by default. This means that it rotates from the point of view of the Transform, rather than just rotating in world space
"2D" is just a camera mode
alright thanks, but how does the whole collaboration thing work, do i push my changes or is it automatic?
Version control is generally not automatic.
You make changes, then commit them.
If you're using Unity Version Control, then read the documentation provided by Unity
you should have a decent handle on how your version control system (VCS) works before you start working
imagine the chaos of version control pushing changes automatically. just in the middle of doing some testing and it suddenly pushes some broken logic to the rest of the team
he is still doing the same? lol
battle royale
So I am following a tutorial on saving and loading. Actually 2 tutorials. I got the player position part right. I can save and load that. But the inventory part is a bit confusing.
https://hatebin.com/weqwrfakpf This the code. I pass the game data reference and just assign the list of container to the game data. https://hatebin.com/dzedeqqeis
But the container seems null on save file.
Show the hierarchy and the inspector for your MouseLook component.
Well, i cant add 2d objects?!
That implies you don't have the relevant packages installed
which implies that your friend has not committed and pushed (or created change sets, I guess, in Plastic) his work
Now select the Player object and show the scene view.
When I quit application i clear the list of container. Then I try to load the scene and my container is empty which leads to not having any items in it.
Set this rotation to zero.
Adjust the player model to compensate.
The point is for the Player object to not be rotated 90 degrees in some random direction
I see nothing here that Saves or Loads any data
ok, i'v done this and i see my problem, the camera is now looking around but the only problem is that the player is lying flat on the ground wich makes is seem like he is still doing weird rotations but he is actually rotating around himself like i wanted to, i just dont know how to let the player stand up so i dont have the same problem as before anymore...
Again: Rotate the player model so that it's upright.
yes but then i have the same problem as before
Why does it say this when im one of the 2 owners of this project
you are in a code channel, these are not code questions
https://hatebin.com/tfdanrfnyj, https://hatebin.com/vszgkdgsyo these two do it
sorry
wow, ok.... it works now, thanks for the help. i dont rly understand what was wrong about it now? why did i need to create that empty object?
When you set your model's rotation to [0,0,0], it is face-down on the floor
It needs to be rotated to [-90, 0, 0] so that it looks right.
This means that its transform is now rotated so that its "forward" direction points straight into the sky
If you try to rotate that transform around its Y axis (the green arrow), it winds up rolling from side to side
because the green axis now points what you'd consider to be backwards
and is there a fix to it without an empty game object?
I think you can change the import settings to bake the rotation into the model?
you can also check "Apply Transforms" when exporting the FBX from Blender
(this can cause problems for models with objects parented to other objects, though)
oohhh, so the problem lies with importing the model from blender?
The acute problem is that your player was rotated back 90 degrees.
But the root cause of that was the model being imported with a 90 degree rotation in the first place, yes
I prefer to just parent the model to an empty. It lets me adjust the position/rotation/scale without messing with the rest of the entity
so because i rotate the empty game object the objects inside it rotate with it
I understand that DatabaseObject is null cos its scriptable object but why the container seems null in save file?
Hey I was wanting feedback on a plan for how to script a crafting system before I dig too deep into it. Is this a good channel to post for feedback since it's related to how I'll set it up in code or should I visit #archived-game-design ?
one thing I notice. Slot does not have a parameterless constructor
No it does not. Why would I need one?
To be able to create one without filling it?
yes, for the deserializer to be able to create an instance of the class
this channel is fine. the question is more about code architecture. i'd start with smth simple. for crafting: you need items and recipes. recipes will have items with the quantity needed, and the resulting item . . .
public void LoadData(GameData data)
{
this.Container = data.Container;
this.database = data.DatabaseObject;
}
I thought this would just copy the slot list from save data and populate it.
This is what I've got written down.
Objective: Have a 3x3 crafting grid the player can put alchemy ingredients that have various mana type values and take up either one or multiple slots within the crafting area.
Item Class - scriptable object that holds data regarding name, manaType, strength, reactivity and amount of the item. This also holds a craftingSize, but it's currently just a placeholder icon.
Potion Class - scriptable object that holds data regarding name, basePrice and amount of the item.
PROPOSED: Recipe class
- contains a 3D array.
- first checks the item manaType values against a ratio to determine which potion the cauldron should craft based on the manaType ratio.
- then checks for a bonus if the user was able to craft that potion against it's designated shape for a bonus.
- instances a new scriptable object to the player based on what potion was the result while subtracting the instances of all ingredients used from the player inventory.
Questions:
-Should the 3D array be an array of dictionaries that check what item is there for the key and then spits out a value that would be the product of another class that returns a manaType, strength and reactivity? Or is there another way that's simpler that sticks out to you?
-I have a 'size' property that currently only holds a Sprite as a placeholder in my Item class. This is meant to eventually hold data regarding how many squares the ingredient takes up and in what pattern they'll be in inside the crafting grid... I have no idea how I'll go about doing this but would a system like the one proposed accommodate this? I'd like to make sure that if an item gives a value of 10 manaType A and takes up 3 of the grids on the crafting square (on a 3x3 UI grid) that it only adds 10 to the crafting recipe, not 30.
before it gets there GameData has to be deserialized
before it is deserialized it should be properly serialized too right? I am not sure what I should be seeing in the save file regarding the container list. But It should not be null right?
Thats why I think it messes up the serialization part.
There should be ID and amount
That depends on your data, as you have zero debugging in that respect who knows?
yes, I know but how to know what public List<Slot> Container; contains?
that is NOT how to debug
I should extract information from the container in code then to see if it actually fills it up
I would add ToString methods to both GameData and Slot so you can output what they actually contain at any given point in time
I did log the ids of the items in the container when they get added and it gives the ids on console.
And that tells you what at the point you want to Serialize the data?
You mean when I save the data?
I just call the Save and load on button clicks. When playing.
I add items then I save
you really have no idea what I am talking about do you
stop playing. Clear the slot container on start. I press load. Player position gets loaded correctly. Slot container is still empty
well I am trying 😄
ok. Step 1. You look at GameData in the inspector, correct?
I do not have a way of seeing it in the inspector because I dont have a monobehaviour class for it
but you told me you can see slots and items being added to it
I see items being added in the Scriptable object which is my inventory.
sorry should've been clear
so how to you KNOW what is in GameData?
Ahh. I logged the slot container's item ids on add item. Not the game data container.
exactly, so you don't KNOW, you assume. That is why I said make ToString mthods for GameData and Slot then you can KNOW at the point of Save and LOad what they contain
I must look up ToString methods and what they mean.
or cant I just make a monobehaviour class to see them in the inspector?
ToString methods are just simple things to help you visualize data, like a Vector3 prints nice in the console. that is a ToString method
Alternatively you could go and learn how to use the VS debugger and save yourself a lot of grief
The item SO shouldn't have a quantity field as that value will change. I'm not sure the difference between the Potion and Item class
The Resident Evil-style (grid-based) inventory is more difficult to code but there should be tutorials on how to check available grid space for items, though it would be a 2D array. Also, the size is probably stored as a 2D array.
I'm unsure what you mean by, "check what item is there for they key and then spit out a value that would be the product of another class." You'd already have the item recipe that is created ,no? Unless you're creating procedural items?
i'v made a movement script but when i move the player teleports a few meters up and is moving above the ground, just floating, is this bcs the player model is created in blender?
Okay I'll look it up. Thanks for the help!
i did a game where i connected both of the players with a line but now i need a damage system for the line i did this script but I don't have a collider that shortens and just scales according to the line.
please write in full sentences
Oh i'm sorry
how are we supposed to know by this alone? think about it for a moment...
show the setup and code involved.
what is the end goal here ? what are you trying to do
simply a damage system that whenever the enemy walks in the line it takes damage.
oh okay, I dont see any lines. are you talking about trigger?
A LineRenderer has a bounds property so you can use that to create your collider, then it will act just like any other collider
whats the current issue and what is happening instead
Do you have any tutorial on that?
no, read the docs, it's simple
right now i don't have any collider that works with this script
in what way ?
are they set to trigger?
yes so right now i have a box collider with is trigger on it but it doesn't follow the line
wdym by "follow the line"
i mean the collider scales down or lengthens whenever it needs to like the line is following the player so it will move and every thing but the collider doesn't move with the line.
you're mixing two different physics controllers , rigidbody and character controller should not go together
also configure your !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
• Other/None
so the trigger isnt following the object?
yeah i have done this but then i still get the bug. im floating in the air the second i press a key to move, i can still move but its just in the air lmao
I don't know how I can do to push objects, I tried using rigidbody 2d for the pushed object, but because it's topdown the gravity is 0, so when I push it, it doesn't stop until it collides with something else XD
Could anyone tell me any method to make this work?
yes
not the trigger the collider overall
what am i looking at here
so thats the camera, its a first person view, showing that im floating lmao
how are you pushing it, it should not be a problem slowing down.. objects dont slow down because of gravity, they do because of Resistance/ Friction/ drag
when i press a movement key it teleports me up in the sky
show the current gizmos of the player in local pivot mode
The item SO shouldn't have a quantity
u mean this? dont rly know what u mean
select the player and show it in the scene view, making sure the top left says Local/Pivot
wdym the collider is the trigger
selected the player, dont know about top left local pivot point in the scene view tho
I cant see the player
press F..aso why is the scale 10..
jesus christ
select the player press F and show me the arrows of the player
jesus christ, i can see the problem 😄
someone knows what to do with this?
why it's showing "Hello, World!"
player is huge
not saved ?
are you trying to do modify items in a foreach loop ?
This is not a unity question
!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
You can't modify a list while foreaching over it
^^ use for loop
Hey guys, i'm having this weird problem with my if statement executing the first condition when it is false. Here i'll show you the code:
Debug.Log(CurrentMovementDirection + " " + (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D)));//This is a debug
if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D)) CurrentMovementDirection = 0;
else{
if (Input.GetKeyDown(KeyCode.A)) CurrentMovementDirection = -1;
else if (Input.GetKeyDown(KeyCode.D)) CurrentMovementDirection = 1;
}
Now, when I press A and D at the same time, the CurrentMovementDirection is equal to zero, which makes sense. But then when I proceeded to moving either A or D, the condition Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D) truns true and I can confirm this with the debug. The issue is that the CurrentMovementDirection variable is still equals to zero, which is still executing the first if statement instead of going to the else statement even if it is false. How is this even possible ?!?
how do change this? i dont find the option
oh, okay, thanks
i told you earlier already, the scale is at 10 rn
Scale in the transform
is this what is making the problem?
I still have no idea what you're trying to do here
that would be a foreach loop yes
They asked you what you mean and you replied "yes yes"
Modifying a collection will invalidate all of its iterators
at least, modifying a List<T> will
ah yes do a backwards loop
for (int i = 0; i < collection.Count; i++)
{
if (someCondition(collection[i]))
{
collection.RemoveAt(i);
i--;
}
}```
you can totally write a collection class whose iterators can handle removal
type forr inside your IDE you should get snippet for backwards loop
Oh, true, I just increased the value of the linear drag and the problem was solved, thx
yes but i wanna make the hitbox a bit smaller lol, i dont know where to find this
by hitbox you mean collider?
att he top on transform thers scale
Make the scale smaller
cause they got their own scales and offset
on the bottom on the collider theres size
Can someone help me here? #💻┃code-beginner message
make ur scale 1:1:1 change the siz of hte collider instead
yess
in short this happens because foreach creates an immutable collection, cause its using enumerator and it causes them to invalidate if you try modifying it. For loops are index based
i dont know where the capsule collider is located
again.. you have scale at 10
it should be 1..
adjust the size on the Character Controller, which is a physics body with a collider already
what is that box collider there for, get rid of it or make it trigger
waitt what, the transform on the player empty object is just the hitbox??? wow, im so dumb
its not a hitbox..wdym
Character Controller is a physics controller component not a hitbox
Think of it a top down game 2D
And i have a laser connected to both of my players but it doesn't damage enemies when enemies go through it.
@rich adder
its not damaging enemies? do they have rigidbody ?
no why should it?
because triggers are physics messages?
i see let me see what will happen
you need a at least 1 rigidbody between the two colliders
No no let me tell you something. When I move the line the collider doesn't move with the line.
What IS the line?
A LINE RENDERER
with this script:
using UnityEngine;
public class LineConnector : MonoBehaviour
{
public Transform player1;
public Transform player2;
private LineRenderer lineRenderer;
void Start()
{
lineRenderer = GetComponent<LineRenderer>();
if (lineRenderer != null)
{
// Set the number of positions to 2
lineRenderer.positionCount = 2;
}
}
void Update()
{
if (lineRenderer != null && player1 != null && player2 != null)
{
// Update the positions of the line
lineRenderer.SetPosition(0, player1.position);
lineRenderer.SetPosition(1, player2.position);
}
}
}
!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.
also show where you put this script on gameobject
i put it on a a gameobject with a transform, a line renderer, and a script which is line connector
So... it has not collider?
Why would a collider move with it then?
yea yea mb
The collider will not match the linerenderer component
yea why
should i use a edge collider ???
Because it has nothing to do with it
You would have to move rhe collider or gameobject
wdym?
private List<IDataPersistence> FindAllDataPersistenceObjects()
{
IEnumerable<IDataPersistence> dataPersistenceObjects = FindObjectsOfType<MonoBehaviour>().OfType<IDataPersistence>();
return new List<IDataPersistence>(dataPersistenceObjects);
}
I have found it. This looks for Monobehaviour derived classes.
public class InventoryObject : ScriptableObject, ISerializationCallbackReceiver, IDataPersistence
This one here is not a monobehaviour so the LoadData never gets called!
I mean that the collider is not affected by the line renderer, it will be affected by the transform and its own properties 🤷♂️
private List<IDataPersistence> FindAllDataPersistenceObjects()
{
IEnumerable<IDataPersistence> dataPersistenceObjects = FindObjectsOfType<MonoBehaviour>().OfType<IDataPersistence>();
return new List<IDataPersistence>(dataPersistenceObjects);
}
Can I extend the findObjectsOfType to look for both monobehaviour and scriptable objects?
yes, use Object
not good practice though
Hi. I have a question: How can I prohibit writing more than the required number in the Input Field (in the text)? For example, I want to limit the number to 10 (11 and more won't help). There is, of course, a character limit, but it is based on the number of characters.
if you only want to accept 0 thru 10 why use an input field and not a slider?
I want to)
then tryparse the input data to an int and test the result
Ok. Thanks
hey
how can I get the forward direction of a gameobject?
transform.forward is world coordinates
that is the forward direction
If you want a local space forward, that's just Vector3.forward
or if you want to be really roundabout, transform.InverseTransformDirection(transform.forward) (:
(which will always spit out Vector3.forward)
so I have this
shuriken.transform.position =
Vector3.MoveTowards(
shuriken.transform.position,
ownerPlayer.transform.forward,
speed * Time.deltaTime);
this doesn't make sense
MoveTowards takes two positions and moves between them
you're giving it a direction
I basically want to move the shuriken forward in the direction facing the player
shuriken.transform.position += ownerPlayer.transform.forward * speed * Time.deltaTime;
This will move the shruiken in the direction the player is facing
Note that this will probably misbehave if you have a Rigidbody on the shuriken
You'll need a rigidbody on the shruiken, yes.
You will also need to either set its position or velocity
You don't want to set the position or rotation of an object that has a rigidbody on it
I do have to rotate it
I'd like to avoid physics if possible for the shuriken itself
is there a way to detect collision without rigid body?
you can use a kinematic rigidbody; however, the other object will need a non-kinematic rigidbody on it
You could also use triggers. Two kinematic rigidbodies can cause a trigger message to occur https://unity.huh.how/physics-messages/trigger-matrix-3d
let me read that
ty
so with a kinematic body I can rotate and move it as I wish right?
I'd suggest setting its position with rb.position, and doing the spinning normally
You can set it up like this:
- Shuriken <-- Rigidbody, trigger collider
- Visual <-- Mesh renderer
Spin the Visual and move the Shuriken
makes sense
so the mesh gotta rotate independently from the rb?
and the mesh should be a child of the rb
got it
I'm having some issues with visual studio and getting some features to work properly and after checking both online and in the #854851968446365696 section on the IDE configuration, I still haven't been able to find an answer. Is this the right place to ask?
did you follow all steps?
show external tools page and VS
As in send a screenshot of my external tools page?
ok try closing vs, click regen project files button. open script from unity and wait a few moments
Should I adjust any of the settings for the generate .csproj files?
no
if it doesn't work, in your solution explorer window inside VS. If it says (missing ) on the assembly file right click it, reload with dependencies or something like that
it can get "stuck", yes
My issue is that while vs is working, I'm not getting the highlighting on a lot of my code and the suggestions that I see other people have under their code is not appearing for me like theirs, only small suggestions as well as not showing me the parameters and I've tried following what microsoft said to do with intellisense but that didn't work, so I figured it's probably an issue with vs code itself
so now its vscode ?
I'm confused here, your externaltools is set to visual studio 
are you trying to use vscode instead? 
yes I understood the problem..
sorry I didn't mean to say vscode, it is Visual Studio 
https://hatebin.com/anemqeapqw So I managed to save the Id and amount to a file by ignoring the scriptable object in my Slot data. Now In my DisplayInventory script. Its having trouble instantiating the scriptable object prefab. Saying its null reference exception. https://hatebin.com/nnqqgzrwau Is this related with not being able to create gameobjects from json?
ok so #💻┃code-beginner message
line 68
Yes
talkPanel.transform.Find("Frame1").Find("Text").gameObject.GetComponent<TextMeshProUGUI>().text = "lmao you have a receding hairline"; giving me a nullreferenceexception
is this code even correct?
debug and find out which one is null
this was an acciddent waiting to happen
find a better way to link your component
serialize the field in the inspector
ohhhh should i do get component in children
just like link it in the inspector
it would be a pain serializing all 8 of them though, i have 8 frames. would it be necessary?
put them in an array if you have 8
wdym how ? by debugging lol
you will literally spent half your time doing that, at some point you have tolearn it
Like I meant I will check what to see if its null or not
yea
okay thanks
inventory.Container[i].item.prefab you got a bunch of stuff here that can be null
Debug them, put breakpoints, or just print values. narrow down
thanks
i know this is unrelated but im curious, is there a place or website where i can pay someone to re format and design my code and make it readable and concise?
maybe upwork or something
i suspect it'd be a lot more work to have someone else fix it than to just improve it on your own, though
i need help with a third person camera script
hello guys , i need help with a third person camera script
ask the question
yeah you said that
my third person camera doesnt follow the player
this is the script
using UnityEngine;
public class ThirdPersonCamera : MonoBehaviour
{
public Transform target; // The target (player) the camera will follow
public Vector3 offset = new Vector3(0, 2, -5); // The initial offset from the target
public float smoothSpeed = 0.125f; // The speed at which the camera smooths its movement
public float rotationSpeed = 1.5f; // The speed at which the camera orbits around the target
public float pitchMin = -20f; // Minimum pitch angle
public float pitchMax = 60f; // Maximum pitch angle
private float currentYaw = 0f; // The current yaw rotation of the camera
private float currentPitch = 0f; // The current pitch rotation of the camera
void LateUpdate()
{
if (target == null)
{
Debug.LogWarning("No target assigned to ThirdPersonCamera");
return;
}
// Get the mouse input for camera rotation
float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;
// Update yaw and pitch based on mouse input
currentYaw += mouseX;
currentPitch -= mouseY;
currentPitch = Mathf.Clamp(currentPitch, pitchMin, pitchMax); // Clamp pitch angle
// Calculate the rotation quaternion
Quaternion rotation = Quaternion.Euler(currentPitch, currentYaw, 0);
// Calculate the desired position based on the target position and offset
Vector3 desiredPosition = target.position + rotation * offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
// Update camera position and rotation
transform.position = smoothedPosition;
transform.LookAt(target.position + Vector3.up * offset.y); // Make camera look at the target
}
}
!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.
can you guys help
obligatory : use cinemachine
@quasi sparrow
i use mirror for multyplayer
the multyplayer works but the camera doesnt follow the player
no offense but you probably should not be doing multiplayer
I know nothing about mirror
what about it ?
the camera doesnt follow the player
have you done anything whatsoever to debug it?
use cinemachine but since you mentioned multiplayer its probably more complex than that
i tried chatgpt 40
nah, it remains simple
no wonder it doesn't work
yeah , thast why i went here
again no offsense but you're using GPT aint no way you're making a multiplayer worth anything functional
Cinemachine works fine in multiplayer
bro do you know how to fix it or
you just tell it to follow whoever the player is
i know but they probably wont know how to deal with the whole IsOwner thing for controlling each cam
e.g. logging some values
I know how I would fix it, by debugging
the console tab is not even shown, also where is the script?
this is the third person camera script using UnityEngine;
public class ThirdPersonCamera : MonoBehaviour
{
public Transform target; // The target (player) the camera will follow
public Vector3 offset = new Vector3(0, 2, -5); // The initial offset from the target
public float smoothSpeed = 0.125f; // The speed at which the camera smooths its movement
public float rotationSpeed = 1.5f; // The speed at which the camera orbits around the target
public float pitchMin = -20f; // Minimum pitch angle
public float pitchMax = 60f; // Maximum pitch angle
private float currentYaw = 0f; // The current yaw rotation of the camera
private float currentPitch = 0f; // The current pitch rotation of the camera
void LateUpdate()
{
if (target == null)
{
Debug.LogWarning("No target assigned to ThirdPersonCamera");
return;
}
// Get the mouse input for camera rotation
float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;
// Update yaw and pitch based on mouse input
currentYaw += mouseX;
currentPitch -= mouseY;
currentPitch = Mathf.Clamp(currentPitch, pitchMin, pitchMax); // Clamp pitch angle
// Calculate the rotation quaternion
Quaternion rotation = Quaternion.Euler(currentPitch, currentYaw, 0);
// Calculate the desired position based on the target position and offset
Vector3 desiredPosition = target.position + rotation * offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
// Update camera position and rotation
transform.position = smoothedPosition;
transform.LookAt(target.position + Vector3.up * offset.y); // Make camera look at the target
}
}
can you at least post the code properly with a link
where
we are in code begginer
doesn't mean you shouldn't be able to follow simple instructions unrelated to code..
and here is the code
using UnityEngine;
public class ThirdPersonCamera : MonoBehaviour
{
public Transform target; // The target (player) the camera will follow
public Vector3 offset = new Vector3(0, 2, -5); // The initial offset from the target
public float smoothSpeed = 0.125f; // The speed at which the camera smooths its movement
public float rotationSpeed = 1.5f; // The speed at which the camera orbits around the target
public float pitchMin = -20f; // Minimum pitch angle
public float pitchMax = 60f; // Maximum pitch angle
private float currentYaw = 0f; // The current yaw rotation of the camera
private float currentPitch = 0f; // The current pitch rotation of the camera
void LateUpdate()
{
if (target == null)
{
Debug.LogWarning("No target assigned to ThirdPersonCamera");
return;
}
// Get the mouse input for camera rotation
float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;
// Update yaw and pitch based on mouse input
currentYaw += mouseX;
currentPitch -= mouseY;
currentPitch = Mathf.Clamp(currentPitch, pitchMin, pitchMax); // Clamp pitch angle
// Calculate the rotation quaternion
Quaternion rotation = Quaternion.Euler(currentPitch, currentYaw, 0);
// Calculate the desired position based on the target position and offset
Vector3 desiredPosition = target.position + rotation * offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
// Update camera position and rotation
transform.position = smoothedPosition;
transform.LookAt(target.position + Vector3.up * offset.y); // Make camera look at the target
}
}
holy hel
You've spammed the same giant blob of code three times
idk is it possible to fix your attitude
💀
you keep ignoring our instructions to post code properly
what instructions
!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.
Please read the bot message instead of completely ignoring it.
and no don't use inline, use link site
i told you there are no errors in the console
so why are you sending the code/
That has absolutely nothing to do with anything I have said.
If no errors appear, that just means that no exceptions are being thrown. It is still possible that:
- The code isn't even running at all
- The code isn't doing anything
- The code is doing something, but it's not what you want it to do
It looks like you guys are having completely different conversations 😅
here i put it on https://gdl.space/zuvecedifi.cs
You should not be attempting to develop a networked multiplayer game if this is your current level of understanding
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Multiplayer is non-trivial.
we can, but you cant understand the fix even if we tell you
here the website : https://gdl.space/zuvecedifi.cs
how to easily cut yourself of any help 101
bro i will stop when someone actualy helps me
blocked, and im moving on.. gooday
This will get you muted.
you should start by putting literally any effort into solving your problem yourself. you seem to have a severe lack of understanding when it comes to the basics, go through the pathways on the unity learn site to learn wtf you are doing first.
i tried
I already told you what to do, but you ignored it.
ok
thanks for noone helping me
You have nobody to blame but yourself right now. Your attitude is unbearable.
@quasi sparrow Keep your usage of this server constructive.
bro this is the first time i used this server in a 100 years
it says the obj is null
you need to figure out which object on that line is null. there are at least 3 that could be
also the itemObject is null
to solve coding problems take a few steps:
- research on the problems you have. if theres an error code, google that.
- rubber ducky: grab any object or person near you and explain your code to them line by line
with sufficient effort, the above two methods will already solve 95% of problems.
for any remaining problems, paste the code thats causing you problems on gdl.space, describe your problem concisely.
we will try to help you but if you havent bothered to solve your problem no one can help you. we spent 2 hours the other day trying to teach someone how types in coding worked. nightmare stuff
The camera doesnt work , i mean follow the player object
I mean the obj that is trying to get instantiated is null because inventory.Container[i}.item is null
thats all i know how to explain
so it cannot grab its prefab
just to double check I'd like to see the script when its dragged onto an object
like the Inspector panel
the player prefab or the camera?
so you need to figure out why it is null. where is it assigned
the camera, the gameobject with the camera follow script
[System.Serializable]
public class Slot
{
public int ID;
[JsonIgnore]public ItemObject item;
public int amount;
public Slot(int _id,ItemObject _item, int _amount)
{
ID = _id;
item = _item;
amount = _amount;
}
public Slot()
{
}
public void AddAmount(int value)
{
amount += value;
}
}
I do JsonIgnore on the ItemObject
Thats probably why
oh youre jumping into networking already?
Which leads back to me not being able to store the scriptable objects T_T
in that case, is your player instantiated by the network controller?
yeah , cause im trying to create a multyplayer game
i use mirror
whats a mirror
yeah if you're just creating instances of this class when deserializing then just never assigning to the item variable then of course it will be null
look this happens when i spawn the player
confused right now. your player is instantiated by the network controller, so why is the target transform set before you spawn the player in?
is there a part where you change the target transform of the camera when the player is spawned in?
perhaps they are referencing the player prefab
yea
none of these images show a game object with a ThirdPersonCamera component on it
uhm can you explain it a bit simpler. I am confused
Is it allowed to send code files or does it have to be links?
send links
what is confusing about that? if you never assign to it then it is null. and since it is ignored in the json serializer then whatever has been assigned to it isn't being saved/loaded because it is ignored.
📃 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.
use these instructions
@quasi sparrow what's happening here is that you dragged the prefab into the slot and expecting it to work. however, the player is not the same as the prefab at runtime.
- go to the code where the player is instantiated
- get the camera controller
- set the camera's controller target to the instantiated player's transform
type mismatch
look at the editor
where are you setting the target?
Yes It is ignored. It adds the id and amount to the save file. How can I make it so that it also saves that ItemObject part?
i first created the game object capsule player and then dragged it into the prefab
So it just deserializes those two
and added all the components
i don't know what ItemObject is, but it obviously cannot be ignored if you want to serialize it
Its a scriptable object
does it need to be a scriptable object?
i first created the game object capsule player and then dragged it into the prefab
using UnityEngine;
public enum ItemType
{
Equipment,
Key,
Misc,
Default
}
public abstract class ItemObject : ScriptableObject
{
public GameObject prefab;
public ItemType type;
[TextArea(15,20)]
public string description;
}
Yes
@eager spindle
I created items based on this.
ok lets do a fun experiment: start the game and spawn in the player as usual. drag the player from the scene hiearchy(not the prefab) into the camera controller's target
ok ill try
then you need to store the SOs somewhere that you can then reference to get access to it
Yes I do that in a database. I hold 2 dictionaries in it
with keys and items so i can access them either way
so if you are already doing that, why are you just not assigning to the item variable using that information?
is it supposed to look like this @eager spindle
Hm uhh
Its my first time trying this. I did some research and people suggest I store them in a Database SO I did that yes. Then like What do I serialize if not the ItemObject SO?
do i add unity version controll so you can see it in the game better @eager spindle
@eager spindle
is that not what your id int on the serialized class is for?
learn to solve your problems without having other people download your project
yeah so when I ignore the ItemObject. I do not even need it written there?
ok
How do I get the items from database back then
to conclude this, your code looks correct but you need to set your target correctly
In load and save I believe
refer to this
after you deserialize the object, you access your database dictionary, provide that int ID to get the correct item object, then assign it to the item variable of the Slot class
you dont want the camera to follow your prefab. you want it to follow the instantiated player.
look @eager spindle
public void LoadData(GameData data)
{
Debug.Log("Loaded");
Container = data.Container;
for (int i = 0; i < data.Container.Count; i++)
{
Container[i].item = data.Container[i].item;
}
}
public void SaveData(GameData data)
{
Debug.Log("Saved");
data.Container = Container;
for (int i = 0; i < data.Container.Count; i++)
{
data.Container[i].item =Container[i].item;
}
}
}```
So uhh this wont work
you dont want the camera to follow your prefab. you want it to follow the instantiated player.
where are you setting the camera target.
look
Hello, if I use this, when the scene is closed and some scripts unsubscribe to an event that has the Game Manager in its own On Disable, sometimes the Game Manager is already destroyed and a new Game Manager is instantiated. So it gives an error, new objects have been created, is it possible that you created them in the on destroy?...
How do I solve this
yeah and what you said to drag the player object there and that doesnt work
this does not appear to be doing what i suggested at all
it doesnt let me
It is not using the database correct
@eager spindle
so then wtf do you think you should do
I should use the database
so do that
Uhh man this is complicated
it's really not
click the Target slot to make sure its highlighted, then click Delete. this clears the reference in the slot. you should be able to drag your player in afterwards
public void LoadData(GameData data)
{
Debug.Log("Loaded");
Container = data.Container;
for (int i = 0; i < data.Container.Count; i++)
{
Container[i].item = database.GetItem[Container[i].ID];
}
}
I did this
and does that do what you want it to?
I swear to god I tried this this morning It did not work
It does work
nope , i tried doesnt work , i tried witha prefab and a game object , but doesnt work
@eager spindle
i can only help you so far
give me 10 minutes and ima break it again. Thanks for the help
You solved a problem I been trying to get right for 3 weeks.
@eager spindle
Not really. wdym
thats why i want you too look better at the project in unity version control
no
@eager spindle
we already told you to help yourself
I learn c# by developing games
well i dont know how
this is something that everyone solves within a couple minutes
literally unlink the reference and double check it
i tried but it doesnt work
the only other way you get blocked from dragging in a reference is if the gameobject doesn't have a transform, which is impossible
you are doing something wrong and we can only help you so far
Did someone delete their message? or am I tripping
well
im miserable at designing pixel art for my dream game, is it then even worth to learn coding c# and unity?
I feel like even when i could climb this wall of learning how to code a game properly, there would be the design aspect
Theres no financial resources id have to invest LOL
i dont know how to fix it
I'm still a newbie in Unity. Thats why I want to ask if my code is correct
https://gdl.space/yawovisutu.cs
It does actually look like the target's properly assigned for like two frames of that video, right when the player capsule spawns. Thereafter it switches to type mismatch... Maybe some weird quirk of the networking library? 🤷
you got this, pick either art or coding to start off first and focus on it for about a year or so. by programming enough you;ll also learn how to break down a game's mechanics into approachable tasks
a year, phew
im 26 already with a fulltime job, just got vacation right now
not sure if id have enough time or if this is appropriate to learn it at that age when life gets real xD
wish id be picking up this when i was 15
The click doesnt work
this would only happen if the networking library is touching the cameracontroller's Target which shouldn't be possible.
im not sure where else Target is set in the code.
never too old to start imo
many game dev seniors started from compsci, specialised in computer graphics and then moved into game dev after years of experience in their field
in their late 30s
you can get pretty far on free assets too
my entire game at the moment is made on kenney assets
i have no knowledge on environmental design but this is what im on right now
look into Kenney's assets, a collection of 2D and 3D assets
How are you actually invoking these methods? Have you assigned them to UI buttons' OnClick Unity Actions or some such?
its more important to plan out on what you want for the game and using free assets that you might swap out later rather than not starting at all
you miss all the shots you dont take, and this is definitely a shot you want to take because its gonna be super rewarding
The buttons and text is assigned to the objects in the script component.
i feel like its thousands of hours of coding and trying/testing for then maybe $0 reward if unlucky
ill think about if i should dedicate years, probably even a decade to this before starting, before being rewarded in any form
all my logics say = dont get started, do something else
but it drags me to gamedev, cant think of anything else throughout the day
damn
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lawydScript : MonoBehaviour
{
public GameObject inticon, teddy, teddyText, lawydText, findoutText;
public AudioSource audioSource;
void OnTriggerStay(Collider other){
if(other.CompareTag("MainCamera")){
inticon.SetActive(true);
if(Input.GetKey(KeyCode.E)){
lawydText.SetActive(true);
findoutText.SetActive(false);
teddyText.SetActive(true);
teddy.SetActive(true);
inticon.SetActive(false);
audioSource.Play();
}
}
}
void OnTriggerExit(Collider other){
if(other.CompareTag("MainCamera")){
teddyText.SetActive(false);
inticon.SetActive(false);
}
}
}``` in my game whenever you interact with the "teddy" gameobject its supposed to play a sound and if you hold e it plays it over and over. i dont want that is there anyway to fix it? (ik my interaction system isnt the best this is my first game)
Sure sure... but like btnA01_Click() is just a method. It won't do anything unless it's called somehow, and your code does not tell Unity to run it when a button is clicked, so I'm wondering if you have set that up some other way, possibly outside of this script
a big drive when I started game dev is to create games that make my friends go "what the ####"
I created a skibidi toilet fangame to troll my friends but I also learned a lot on how to publish to the google play store
by doing fun projects youll be more motivated to create more stuff and consequently learn more
I havent assigned the method to the button.
the best thing to do would be to start with redesigning your interaction system. because the normal advice would be to use GetKeyDown however that is likely not going to work in OnTriggerStay on account of that method only returning true for the first frame the button is pressed which is most likely not going to be a physics frame.
Look into using raycasts to interact with objects instead of copy/pasting this same interaction code on a shit load of different objects. you would instead have one object controlling interacting with objects and those interactable objects can then just do their own thing when interacted with instead of having the objects themselves check for interactions
Is that what you're asking then, how to get that code to run when a button is clicked?
yes. I dont know how to assign a click method to an button
improving it on my own would mean i would have to rework everything because i may or may not have messed my code up lol
hello guys! Sorry for interupting, do you know why i keep getting this error when i want to create a 2D game?
that makes it even harder for someone else to come in and "fix up" one part of it
yes but im paying him to fix it, so it shouldnt matter how hard it is
the code is really messy i should be paying him extra i cant lie
Gotchya 👌
Assuming you're using UI Buttons that are children of some Canvas, you have two options:
- In the Inspector for the button, there will be an
OnClicksection. You can add callbacks there, and drag the GameObject with theTicScriptcomponent from your hierarchy to the new field, then select yourTicScriptand the appropriate method from the dropdowns. Here's a video of that in action - In code, you can subscribe the method to the event. Something like
void Start() {
btnA01.onClick.AddListener(btnA01_clicked);
}
See the docs for reference - switch to the docs for your specific Unity version as things have changed a bit.
The buttons are in Canvas/panel/btnObj
Cool cool - that sounds fine. Just wanted to be sure this was Unity UI, and not a button in one of Unity's other UI solutions (IMGUI/UI Toolkit) 👍
No I use legacy
Oops - my little example and the documentation link I provided were for UI Toolkit. I've corrected them 👀
What does that mean?
hey guys, i'm trying to move my 2d sprite slightly left per frame- instead it goes flying. any ideas on how i could require a longer input to fully turn it? it just goes flying atm lmao, which makes sense because it's 60 degrees per second
if(Input.GetKey(KeyCode.A) == true) { //MOVE LEFT
Player.transform.Rotate (0, 0, 1); }
You should be using Time.deltaTime if this is in Update
Also this isn't moving anything, it's rotating
oh, i completley forgot about that command! thank you :)
right right
private IEnumerator SpriteBlink()
{
for (int i = 0; i < 4; i++)
{
attackButton.GetComponent<Image>().enabled = false;
yield return new WaitForSeconds(0.1f);
attackButton.GetComponent<Image>().enabled = true;
}
}
this thing wont work for some reason it only blinks once for like 1 second then comes back, not 0.25f every time
You need two WaitForSeconds, one after setting enabled to false and one after setting it to true
oh yeah now that i think about it
thanks!
Hey guys, I was wondering how to actually learn clean code, I think I have the basics of C# down, but I cant figure out OOP. I just cant seem to figure out when to use Inheritance or Intrefaces or any stuff like that, how could I learn this?
since i dont want to learn stuff i dont want to learn yet id like to learn stuff i would like to know
So with unity i want to create a 2d open world survival craft game. Id like to know how to create a procedural generated world thats basically infinite by generating new tiles every time.
It should contain: Biomes, chunks, have a seed (so its random and choosable)
what would the technical stuff look like? like i would need to create a class for chunks, a class for biomes and an int/float for seeds?
What is the child of what?
What c# stuff i would need to know to make this possible
like i guess classes
else and if functions?
What more?
thats a super heavy project, this is the beginner channel lol
i'd reccomend finding a procedural generation addon and spending time learning it
that's pretty complex
Well, yes, you need to know the absolute basics like classes and conditions. That would be the case for any kind of game.
You basically need to know every basic thing.
Just do everything here
https://www.w3schools.com/cs/index.php
Hi, took a break from unity but coming back I still haven't managed to solve the problem of what is happening to the Ai animation, please help :)
Problem: Enemy is jittering and not running / playing running animation smoothly
Expected: Enemy smoothly runs to the Player.
Thanks :))
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 the only thing being sent to the animator?
animator.SetFloat("Speed", 5f);
what happens if u lock it in place?
same thing
then its not the code
im awful at blend tree's sooo idk if i can help
@swift crag i had him set the float to 5... too see if it was the fluctations that caused the problem
as u can see in his video it still glides along the ground..
so im thinkin its something with the animation. or the blend tree.. but idk
Do all of your walk animations line up?
@lethal swallow ^
by "line up" I mean that the left and right feet are doing the same things at the same normalized time
All animations should have the left foot hit the ground at, say, 25% time
It shouldn't matter if you're at a speed that exactly matches one of the blend tree values
so perhaps one of your animation clips isn't looping
^ could be.. id check ur clips @lethal swallow and make sure ur blends are set up w/ looping animations
you can change the names of animations in the Animation tab of the model importer
imagine its just b/c the animations aren't set to looping..
cuz ive seen him working on this for a whiile now
Yes, that's exactly what this looks like
When the speed is changing over time, you'll see it wobble between the last frame of the different animations
can anyone point me a video or blog to maybe explain how I could achieve this with my camera? I've worked with cinemachine on a topdown isometric view but ive been trying to achieve this for a while now and cant 🤦♂️
Dolly track? focus on center?
Check out the "hints" on each camera
exactly
sorry for going afk for a few mins I will try these things and let yall know. Thanks :)
you can tell it to spherically interpolate between two cameras
its just pivoting around a center point @vapid vector
This will give you that effect for free, even if your cameras aren't actually both looking at a central point
And it's actually necessary, too, if you want to be able to transition between two cinemachine cameras
does it have to be cinemachine or can i do this with regular camera? I was trying to get 2 cinemachine in the right place and swap between them, but i seriouslt cant get the cinemachine in the exact spot i want since theyre like smart and whatever and calculate position alone
Yeah two virtual cameras is actually easier
Even if both cameras are looking at a central point, the default behavior is to move linearly from one camera to the other
Use a dolly track if you want more precise movement from point to point
You can set the exact position of a cinemachine camera
Give the Blend Hint property a look.
"Cylindrical Position" would be the most fitting here
It moves circularly on the XZ plane and vertically on the Y axis
facts... i think this idea is better.. 2 cameras at different angles.. swap cameras for each battle cycle... but its also similar to a god-camera setup..
the camera tracks a pivot point in the center.. and can rotate around it
but (2) 📷 are much better idea
You set the Blend Hint on the camera you are blending from
This is pretty nice, but Fen's suggestion is a lot better overall
wait wat did he say?
But since you're going back and forth, you'll want to put it on both
ohh yea Fen's smart guy lol
Cylindrical lerping is really handy
They're just suggesting to mess with blend hints between the interpolation
I wound up re-implementing as a function that works much like Slerp
ahh yea.. that'd work
whats the ELI5 reason to use Slerp..
Spherical interpolation on two axes and linear interpolation on a third
i have some rotations and i lerp them.. it seems fine..
but i never use Slerp.. and i think i should refactor
For two points that have the same distance from the origin, Slerp is like moving on the surface of a sphere
Yup after checking they all are @ around 31%
I am less clear on Quaternion.Lerp vs. Quaternion.Slerp
I'm guessing it's similar to how they differ for Vector3
Right. But don't quote me on that one
If the distance differs, you smoothly change the radius as you move from one point to the other
pardon my stupidity how would i do that
double click the blend pieces on the right..
you'll see the animations
or click the animation.. and in the inspector.. set looping
Looping is not configured in the animator controller, mind you. You need to change how the animation clips are getting imported.
^ this.. in the inspector
I presume you've downloaded some FBX files from Mixamo
yup
Click on one and go to the "Animation" tab in the inspector
here, you can configure how the FBX gets turned into animation clips
You can create multiple animation clips from one file, set when they start, configure root motion, and, vitally, decide if they loop
|| the weren't looping the entire time ||
its just that cinemachine has been a little overwhelming for me, im never sure what to use but I'll give your advice a shot thanks @swift crag !
I would start by just plunking down some plain old Cinemachine Cameras in your world
yea.. they're all basically the same.. w/ different setups and components..
shoot
No position or rotation controls at all.
but u can make any do like any other
Try turning them on and off in play mode
Change the Blend Hint settings and see how they affect the blending process
ya, its not as complicated as u think it is @vapid vector
(don't tell anyone that I have no idea what this does though)
do I just turn on looptime
the cinemachine camera.. just takes the real camera.. and plops it in its place...
"Freeze When Blending Out" is really handy for jumping away from a camera that's moving around a ton
Correct.
You can also enable "loop pose" to try to make the start and end match if they don't already line up
but Mixamo animations already loop perfectly
Bit intimidating at first but after getting familiar it's pretty intuitive and quite powerful, you won't regret putting the time in
i dont build a camera system unless theres a VCam in there..
even if i dont use it.. i want it to be a cinemachine camera.. just in case
I use a very large number of virtual cameras in my game
Yeah, Vcams make scene cameras and game cameras a breeze
You can do loads of cool things with an extremely reduced amount of scripting
I do want to modify the package a bit to give me more control over how long blends take
except i think the newer cineamchine doesn't call em vcams
it might.. but i dont see it in the window drop down anymire
They don't?
yeah, they're just "cinemachine cameras" in 3.0
just cinemachine camera
it is a bit less concise
I'm still on 5
Fen and Spawn tysm 💚
It finally works 🎉
cinemachine 5.0 🤯
wooohoo hell ya 👍
LOL
thanks fofr sticking with me
By the way, if you're having problems with the velocity rapidly going up and down...
no worries mate.. 🍀
https://docs.unity3d.com/ScriptReference/Animator.SetFloat.html
I just noticed that there are a few overloads I've never used before.
public void SetFloat(int id, float value, float dampTime, float deltaTime);
It looks like you can have it do a smooth-damp for you
Guess I'll have to update my cinemachine... not for this project though lest it breaks everything
thers a Dampen!?
great ty
holy crap..
animator.SetFloat("Foo", agent.velocity.magnitude, 0.3f, Time.deltaTime);
ya,, i wouldnt risk it if u have a heavy reliance on cinemachine cameras
In theory, this would be equivalent to using Mathf.SmoothDamp to smooth out the magnitude yourself
stick to the version u used
There's no huge impetus to upgrade
One big change is that the "free look camera" is no longer a completely unique class
you can create it with standard position and rotation control components now
Yep no way, it's making heavy use of virt cam switching and the like. I have at least a dozen cameras per level I think
you've been investigating it seems Fen
That's nice, I'm sure there isn't a massive amount of new features that I need but I'd hate to be midway between a project and think... you know what maybe I do want X extra feature
So future Mr!
It's got some nice new stuff (including a few things I asked for, haha)
Me* shall remember!
bak
I'll have to check the changelog
CinemachineDeoccluder has the option to resolve towards the Follow target instead of the LookAt target.
I was using it for a Dark Souls-y game
Ahyep, I'm on 2.9.7
but I had a problem: when locked onto an enemy, the look-at point was positioned between the player and the enemy
I'm missing a major release
and if that point went into a wall, the camera went bonkers
now you can just have it keep the follow target in view
2.x is going to be supported for a long time
but maybe give it a try on a branch
cinemachine obstacle avoidance.. is subpar imo
Worth a shot honestly, thanks for the headsup! I like tinkering with new things
dont we all... 😈
stay away from the rabbit hole..
I remember back in like 2013/2014 I was making my own obstacle avoidance system for cameras, it was not straightforward nor fun
I'm okay with Cinemachine's implementation for the most part
@swift crag i got a question for u since ur right here... how do u have ur scenes collected? how do u call upon them?