#💻┃code-beginner
1 messages · Page 162 of 1
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] int speed;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
speed = 5;
}
// Update is called once per frame
void Update()
{
float x = rb.velocity.x;
float y = rb.velocity.y;
float z = rb.velocity.z;
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
if (Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector3(rb.velocity.x, speed, rb.velocity.z);
Debug.Log("Jumped!");
}
if (Input.GetButton("Vertical"))
{
rb.velocity = verticalInput * speed * transform.forward;
}
if (Input.GetButton("Horizontal"))
{
rb.velocity = (horizontalInput * speed * transform.right, y, z);
}
}
}
this wont work
and i cant figure out
how else to do it
then you have somewhere else changing the Y val
for my object it's right and left
and you are still passing vector3 for a x parameter
no
that was showing
that wont work
*that was for showing
so what else can i use
dude
i removed that already
did you read my messages
i know why its not working
yes
OH
i just
understood what that does
😭
my brain is a little slow
so essentially manipulate velocityvector instead of rb.velocity
and then declare rb.velocity the same as velocityvector
right?
if (Input.GetButton("Horizontal"))
{
Vector3 velocityVector = horizontalInput * speed * transform.right;
velocityVector.y = y;
velocityVector.z = z;
rb.velocity = velocityVector
}
Ignore cow rotating when moving forward
no
i understood that
ty
it's because something else is wrong
wait why are we doing velocityvector = .... instead of velocityvector.x = ...
thats a question i got
jezus xd
OH
you cannot set x to a vector3
I'm not even sure where does it move, but it moves to some specific direction and that's what I don't want
!warn 756739408379510814 Please remove the transphobic meme from pronouns or you will be removed from the server.
norwxy has been warned.
im trying to make a laser pointer but it seems like it has a delay when looking around with the mouse. Any smart fix for it?
if (Physics.Raycast(laserStartPoint.transform.position, laserStartPoint.transform.forward, out laserHit, 100f, ~ignoreLayer))
{
if (laserHit.collider != null)
{
lineRederer.SetPosition(0, laserStartPoint.position);
lineRederer.SetPosition(1, laserHit.point);
}
my bad i had that from a while ago and forgot to remove it 😅
dw i aint transphobic
Most likely delay is related to movement and the timing when this is called.
Put debug messages where this is called and see if they are delayed
It's in the update function so it should be pretty accurate, no?
then keep dropping debug messages up the chain to find the source
This involves physics as well so will be executed on physics frame (not sure exactly when raycasting is called in this case)
You can have more Update cycles before it executes
can anyone teach me how to make a better map for my 2d rpg game?
this is a code related channel mate
There's nothing in this that involves mouse movement so potentially the code that rotates (?) the laser pointer is what causes the lag
it's only not execute if i looking up the sky and the raycast cant find a collider
nothing in this code could cause delay
Well then idk what causing this. (the delay, not when i look up to skyebox and it lose the connection)
Yea, it looks like raycast would give you an immediate result in Update or FixedUpdate, but if you expect to see changes affect something physics related, those will be only after next Physics frame.
It breaks when you look up because there's no hitpoint in the empty sky
The visual for this also doesn't even need to be updated.. just have it as a child of the gun, positioned correctly, and toggle it on/off
Yea, i know that but it's not about the break, when i walk right or move mouse the line cant follow the gun smoothly
the start point is a child of the laser attachment which is a child of the weapon.
but yea i might end up using some photoshoped image instead of this stupid linerenderer
!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
You've got to install something to code with
ok
Notepad 
@restive ore You should start with a Unity course explaining basics https://learn.unity.com/pathway/unity-essentials
Is there anyone here that is good at 2D games, im currently trying to make a scenechanger but my player is not colliding with the scenechanger object that i have created, and i cant for the love of my life find what the problem is.a Any help is greatly apperitiated! ❤️
im actually watching a unity tutorial rn
but then suddenly he just randomly start scripting
So follow a proper course I've linked, not random tutorials
make it trigger and use OnTriggerEnter2D
ok
but now im in visual studio
i pressed unity
game development with unity
do i have to press C++?
@restive ore course explains everything, including VS install
Yeah i have that and i have made sure that they are on same layer etc, and i even put in a Debug log and nothing is showing 😦
Do you have a Rigidbody2D on any of the two colliding objects?
I have it on my player yes
That didnt really help but ty anyways, i have been looking at that page all day yesterday. Something is just wrong and i cant find it 😦
start with screenshots of the inspectors of your 2 objects and post your !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.
I posted the bot for a reason
i dont understand how it works sorry im new here
You're using OnCollisionEnter2D and both colliders are set to Triggers
So you failed at following this, which explicitly takes you through this setup 😄
Does anyone know how to fix this, it gets an error everytime i press space😭.
rb is null because you never assign it to anything
Yeah, assign your rb
And don't post photos
well i did that and i tried having both on, having 1 on and other off etc. but still not working so
Ah sorry, thanks
The player boxcollider doesn't need to be a trigger if the scene changer's is ticked. also should work:
public void OnTriggerEnter2D(Collider2D collision)
{
if(collision.CompareTag("Player"))
{
Debug.Log("Player is colliding");
SceneManager.LoadScene(sceneToLoad);
}
}
remove the rigidbody from the scenechanger too.. you only need 1
and this tells you what if
A) Nothing is colliding
B) It Collides with something other than Player
?
Yo. i got 5 extensions installed at vscode : unity ,C# , .NET, C#dev kit and intellicode. They take 2.7gb ram, which is concerning. is this normal?
If you downloaded them from within VSC, yes ..
ok so now i changed the code, i removed the rigidbody from screenchanger and i only have the trigger on the LevelChange object. And still nothing is working, im losing my minddd
Put a log before the if statement to make sure the collision is happening
public void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log($"collided with {collision.name}");
if(collision.CompareTag("Player"))
{
Debug.Log("Player is colliding");
SceneManager.LoadScene(sceneToLoad);
}
}```
Nope they are not colliding because im not getting a message :/
When player collide with tagged "Enemy", enemy acts like player has powerup. İ dont want this but i couldnt find where is the problem?
Do a screen recording of what's happening, let's see if that shows anything
hasPowerup is true.. find out why
what?
The variable hasPowerup is set to true
Oh, actually.. your condition is
if ((enemy) OR (enemy fast AND hasPowerup))
so any normal enemy will trigger the first one
You'll want to put brackets round the enemies
if ((enemy OR enemyFast) && hasPowerup)
or not
because of the logic, look at the difference between the two statements
i saw
Sorry i had to listen through it since it had audio lol
thankss
ah alright, do you know if there is a way to reduce it or not
hello! I'm having an issue with my code (atleast i think it's code related)
In the inspector, it keeps tellign me "Object reference not set to an instance of an object" but i cant find any references that dont have objects set? And it doesn't cite any code, just some long list of things related to an animator. THe animator currently isn't working, the clips, start and end states aren't showing up, even though i deleted the whole thing and made a new one. I think it is an issue with the object I'm trying to animate, but i can't figure out what it is.
argh, why did you not show the inspector
haven't got a clue
alright thank you
That's not your code, it's an Editor bug. Restart Unity
Oh epic, thanks!
I have been trying to figure that out for half an hour:)
I’d just use regular vs
Here you go @hexed terrace
The UnityEditor bit is a bit of a giveaway
Alright, I'll look out for it in the future
you should never get UnityEditor errors unless you write your own Editor code
👍
It worked
thx
oh side note, any reason why this isn't jumping?
What are you doing with these two layer fields?
Remove the time.deltaTime from the jump equation
the top one if for collision objects so i cant go through certain objects and the other one is so i can interact with specific objects when pressing E
It's possible this affects your trigger collision
want me to send you the code?
Also, due to your code, jumping will remove all horizontal velocity. Is that intentional?
wait it does?
@hexed terrace if you wanna look at the code here it is 👍
Yeah, but setting the velocity instead of adding to it, you’re resetting the horizontal velocity to zero
no it doesn't
but i keep my velocity when i jump
I just tested it
oh wait maybe not
I was wrong yeah
You’re setting transform.position for horizontal velocity so yeah you’re good
Mb
alright! I'll keep that in mind tho, i didn't know you could add velocity instead of setting it
Yeah, it’s .addForce or something
Or just += to the velocity
huh, okay I'll have to go look tha tup
!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.
out of curiousity, is there any easy way to set where a player spawns depending on which scene you just left? or do i just need to make a logic script any a bunch of variables?
I honestly dont understand how to paste code with that tool
you could make an object with dontdestroyonload that has a reference to the last scene
a variable reference to the last scene you were in
https://paste.ofcode.org/vFFGdjMGUP3WDFS3LswNG5 @hexed terrace
what would i use to make the variable match the last scene? is there something built in for that already?
i dont think so, you'd need to take care of that yourself
you could make it a singleton to set it more easily
whats that?
It's real simple. Open one of the web pages, copy/paste your code into it, save it, then post the URL here
how do I do that? Is it just something I declare at the start of the script?
using UnityEngine;
using UnityEngine.SceneManagement;
public class LastSceneManager : MonoBehaviour
{
public static LastSceneManager Instance { get; private set; }
public int lastScene;
public void Awake() {
Instance = this;
}
public void SetLastScene(int sceneId) {
lastScene = sceneId;
}
}
then you can reference it anywhere in your scripts like this:
LastSceneManager.Instance.SetLastScene(0) //for example
let me know if something doesnt work i dont have unity to test if it works lol
you can also just directly do
LastSceneManager.Instance.lastScene = 0;
``` btw
You're not using physics to move, so you won't get collisions
So how am i colliding with my NPC:s, enemies and colisionobjects?
Vector3 newPosition = transform.position + new Vector3(direction.x, direction.y, 0) * speed * Time.deltaTime;
// Check if the new position is walkable
if (IsWalkable(newPosition))
{
// Move the object to the new position
transform.position = newPosition;```
this is just teleporting the player to it's next position each time
i forgot to also add, change it to this so it stays between scenes:
using UnityEngine;
using UnityEngine.SceneManagement;
public class LastSceneManager : MonoBehaviour
{
public static LastSceneManager Instance { get; private set; }
public int lastScene;
public void Awake() {
Instance = this;
DontDestroyOnLoad(this);
}
public void SetLastScene(int sceneId) {
lastScene = sceneId;
}
}
then add it to a random object in the first scene
your iswalkable method checks
thankyou! Do you mind i fI ask some questions so I can understand what it does better?
sure go ahead
What does the "Instance = this" do? is that a reference to something?
do you have any god fix for this or am i fked? I have mostly been following youtube tutorials since im new at this so
the this keyword references this script basically
this script in this object
Oh alright, so what does the instance do? is it saying any mention of "Instance" is refering to this script?
of course you're not fucked.
it works the same as ```cs
GetComponent<LastSceneManager>()
do you mind helping mea finding a fix? i really aperitiate all the help you are giving me
it sets the static variable Instance (static meaning it can be used in ANY script) to this exact script in this exact object
Okay. So any mention of the variable Instance in ANY script is refering to this script?
it doesnt need to be named instance btw, it can be named singleton and whatever you want
but yes any mention of the variable LastSceneManager.Instance is refering to this script
but of course there can be only one object with this script then, since more will just overwrite each other
Alright, that makes sense! Sorry for all the questions, I just find using code I don't understand gets me even more lost
You either need to change to using forces to move, so you're actually using your RB.. or.. you could just use existing code to make your own trigger.
It'll be easier to do your own thing.
I'm not going to hold your hand through it.. look at your Interact() and IsWalkable() methods, look at how they detect things.. use that as the base for your level change. Doing this means you can remove rigidbodies from the player etc
What does the { get; private set; } do?
i shouldnt have written like this to be honest lol especially if you dont get it
but basically private set means it can be only set by this script, even though its public
haha, I'm so used to Visual studio code automatically doing the other half o f the brackets i totally forgot to do them
you can totally remove it
okay, neat
You still need a safeguard or when 2 instances exists
so i just add LastSceneManager.Instance.SetLastScene(0) to my trigger before it switchs scenes?
Allright, i think i just have to start over in that case cuz i dont know muich about this, let alone changing and using code i have allready written, but i really wanna say thanks for the help ❤️
yes, the 0 is the scene index
Whats the best way of going back and re-getting a random array element?
void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
}```
yes you can do that too for safety
you can add that to the script
what is this for?
safeguarding
agaisnt what?
if there's more than 1 object with this script it'll destroy the rest
and keep only one
You do not have to start over at all.
Look at this code, copy it into a new method and THINK about what you could change/ do to check for another layer 🤔
if you somehow happen to have a copy in another scene
oh okay
you dont want to ovewrite it
is there a way to write a if statement which also generates the random element?
make a method that returns the random element?
idk what ur asking tbh
you can just copy and paste it of course but that looks ugly
yes DRY code
private GameObject GetRandomModule() {
return CityModules[Random.Range(0, CityModules.length)];
}
you could add this
if citymodules is in the scope of the class
I'm trying to make it so it will re-roll it if it was the same city module as the module before
if that makes sense
isnt this correct? i still get a NullReferenceException: Object reference not set to an instance of an object Fireball.Update() error
use a while loop
give it a max iterations too as a guard clause
do you have line numbers disabled?
I'll try it out, thanks
so if I wanted to check what the last scene was, would i still need to reference this script?
ohhh sorry i didnt know which one it was, line number is 6
This code has nothing to do with the exception.
it would just be LastSceneManager.Instance.lastScene
The exception is on line 17 of Fireball.cs
line number is 17 on diff script
You've shown us FireballSpawner.cs
alright, thanks for allt he help!
yea i thoguht that might been the case too but got told to post here
nah bro this is the right channel
you just sent the wrong script
capish?
Assets/Scripts/Fireball.cs:17
Fireball.cs, line 17
there we go
Turn on line numbers in your editor.
now why are ur efin lines disabled
They will make your life significantly easier.
idk thats how my vs was when i downloaded
:doubt emoji
The default configuration for visual studio has line numbers enabled.
oops, this is...a random language
serbian!
well, the actual article isn't translated
also next time you can double click on the error
ok there we go
ye i asked one on my class but bro i didnt change anything
so playerMovement is null
but ye i got it on now
the script worked when i didnt spawn a fireball via a "spawner" why would there be a problem now
because playerMovement is null...
did you assign it in the inspector?
A prefab cannot reference a scene object.
So there is absolutely no way for the fireball to have a reference to playerMovement as-is
you'd have to set it through the fireballspawner script
bingo
yes you need DI
but when I hear "DI" I think of 34-layer casseroles of wildly overcomplicated containers and frameworks
I use this 🙂
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-8.0
Learn how ASP.NET Core implements dependency injection and how to use it.
the fireball spawner is in the scene, so it can reference a PlayerMovement in the scene
then it can assign the playerMovement field on the fireballs it instantiates
the unity version 😛
https://unity.huh.how/references/simple-dependency-injection
Vector2 vec;
vec.x = 3; // dependencies injected!!!
⚠️ extreme DI in progress ⚠️
im scared of people who write initialise instead of initialize
are they or I think aussie, same tomatoes xD
ok ok so the problem is when i assign this in the inspector, as a perfab it doesnt save it
the Player Movement
Will this work? So it will keep calling newModule() until the previousObj isn't equal to next module?
You cannot add scene references to prefabs
Prefabs can't reference scene objects. What if you spawned the prefab in a different scene?
first i'd put an iteration max as guard clause
if somehow previousObj is always NextModuleObj you're stuck
Hey guys i made a 2d soccer game and i wanted to test it out with my friends online, do you have some sort of tutorial to do that?
like setting up multiplayer etc
also what is newModule do
i tried tarodev one but i couldn't accomplish much
if you made it... it wont be that easy to convert
especially if youre starting out
the tarodev one is the closest you'll get to your thing
ye exactly what i tought
multiplayer isnt trivial
why not just return and obj
How would I put a iteration max?
instead of void
i saw that x)
How would these work?
so any idea on how to do that? like should i make it from 0 while adding multiplayer at the same time or
int maxIterations = 50000;
int i;
void Method()
{
while(something && i < maxIterations)
{
//do work
i++;
}
}```
Is this something you want to happen over multiple frames?
you'd need to understand basic concepts of multiplayer if you dont know them yet
just return the CityModules[Random.Etccc.
change void to whatever type that returns
ye i know close to 0 about multiplayer, started with unity 3 days ago
soo i'd start with a new simple multiplayer game made from a tutorial
just had some knowledge in c
i recommend mirror or fishnet, i dont recommend photon
dont make a multiplayer game
when you are just starting with unity
why would you shoot yourself in a foot
ahahah
3 days in unity you should not be doing multiplayer at all
i didn't think it was that hard
no one does
my bad then 😛
I don't understand
they think its like roblox or something
never played roblox but i get what you mean
do you not know how to return another value besides void in a method ?
some knowledge.... have you used socket?
public class SomeType { }
SomeType somethingCool;
SomeType Method()
{
return somethingCool;
}```
ohh I think I've played around with this a little
basically this
#💻┃code-beginner message
guys is alteruna a scuffed multiplayer version?
righttt ok, that makes sense
you should learn more about what you're doing before shopping for multiplayer frameworks
i'm just asking
frameworks are made different for diff use cases / needs
you have to know your own cases which you gain by experience. Not by jumping head first in a shark tank
@hard hornet It's working perfectly! That you so much!
so whats the point of doing this over the way I had it?
Never said i wanted to buy alteruna (didnt' even know you could tbf). I just saw that tutorial yesterday and it felt like a short, not so-good way, of transforming your game into a multiplayer
its more implicit on what it does
Hey just a general question, when im coding in Microsoft visual studio i dont get any colors for classes, functions etc. But all of the people that are on youtube does. is there some kind of package that i have to download? It makes it really confusing when everything is the same color.
Would you do something like so?
yes
int maxIterations = 50000;
int i;
void Method()
{
while(prevModule == nextModule && i < maxIterations)
{
//do work
nextModule = GetRandomModule();
i++;
}
}```
also how many max iterations would you let it do?
Also everyone im watching seem to have previews of different things to write where as i have to do everything manually. is that also some kind of addon / extension?
!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
up to you really what number it is, i choose 50,000 but can be more or less. How many times should we try before it stops
It wants me to put = something after i?
int i = 0
you have not assigned a value and its a local var so needs init
but then surely it wouldn't count up?
Ohhh wait its a while, not an if
yeah that makes sense
this fixed the problewm
dont use Find methods
😢
i dont understand why not just Inject it on spawn like we suggested
ngl i didnt understand stuff from the link u sent
Thanks for the help :D
@slender cargo are you trying to make this while loop happen over multiple frames?
I have unity addon installed through viual studio but i dont get this like the guy on y outube does
!vscode
which part you dont understand? the object that spawns it (spawner) passes its scene reference(Player) to the object spawned
hmmmm one moment ill try
actually you dont need to loop to find a random thing
int someInts[100];//some ints here
int choices=100;
each time when you get a random value from someInts
int index=rand()%choices;
int val=someInts[index];//swap the value with back
someInts[index]=someInts[--choices];
someInts[choices]=val;
btw ty on the cellular automaton recommendation, Tina. It helped quite a bit
this is hella confusing for a beginner no?
the basic idea is remove the chosen item from current collection and put it in somewhere (maybe you need to reset it)
i just put it in place
if you need a uniformly randomly distributed item from an indexed collection, you can just select a random index
true
is this right?
Bingo!
thats one way to do it sure
can i shorten down to this
you could just make this a public Fireball fireballPrefab;
Vector3.zero
you dont need new Vector3
now you don't have to do GetComponent<Fireball>() -- Instantiate will just return a Fireball
evenb etter
oh for that i had cuz im likely going to change the spawn point, just have to 0 for now
oh wait it local var.. nvm
I would prefer to use Vector3.zero anyway
lika dis?
how to make missing (game object) in arrays null? i tried by comparing tag in every index
{
rockAmount[i] = null;
}```
but it stays at missing and i cant replace it with another gameobject
why is it missing in the first place ?
you should use ScriptableObjects instead if you have items in list that destroy
is the middle of the scene 0, 0 ,0?
thats the origin of the world
hmmm
its now spawning the fire balls at the origin and not at the spawner itself
well yeah you wrote 0,0,0
world pos
i wanted the local 0, 0 ,0
if you want the spawner position just pass the spawner position
oh ye
I'm not sure if the inspector will update after you set an array item to null
I don't see how this would stop you from assigning a new game object into the array. Gonna need some more context here.
use a list and remove the element 😈
i use destroy() to delete gameobjects then i have fuction that checks if any index in array is null and makes new gameobject
okay so what the fire ball does now is move in a sinus wave, rotating towards the direction its moving to, but also following the player.
right now however its turns after the player in a sharp manner and feels unnatural.
My solution to this would be to not update the players position every frame, but instead every 10 frames maybe.
Timers and such is also something that confuse me and to time stuff i use DateTime
so the way id solve this rn would be to have an if statement that checks if the DateTime timer is equal to or less than the current date (if its now or already happened), and if it has, it updates the players position but also sets the DateTime timer to current date + 0.5seconds, would this approach work?
Time.time is the time since game start in seconds
you can use that basically identical to how you're currently using DateTime
is it like best practise to use that?
you generally care about in-game time, not about real world time
for example, if you pause the game, cooldowns shouldn't be progressing
unless u want to shame the player for not playing for X: amount of time 😄
Okay so I have this piece of code on my player to stop them from colliding with the fence tile map, and it's still colliding, do I need this code on the tilemap too? or have I written it wrong?
Physics2D.IgnoreCollision(fence.GetComponent<Collider2D>(), GetComponent<Collider2D>());
It's in void start by the way
wait nevermind I forgot to actulaly asign the tag
lol
ohhh
i see
but otherwise the structure would work, ye?
dang cant use add seconds tho
or ill just do + the number
like + 0.5
im using public MonoScript attack; for getting an interface into an Scriptible object but when i trie building the game i get this error
error CS0246: The type or namespace name 'MonoScript' could not be found (are you missing a using directive or an assembly reference?)```
something like this i suppose
show the full error stack
are you not getting underlines in your IDE btw
Time.time is a float.
So, yes, you just add a number to it.
There's no need to add all those (float) casts.
MonoScript is in the Editor namespace only
It won't work in a build
is there another way to make it work in build?
Why can't you reference a ScriptableObject?
to link an interface into an scriptible object through the editor
What would you do with that interface
a MonoScript is the actual script asset. it has nothing to do with the classes defined in that script
I don't understand what "linking an interface" would entail
Are you trying to serialize a field of an interface type?
I don't think interfaces are accessible from the inspector without customizing the editor
You can't do that by default. Unity will only serialize types deriving from UnityEngine.Object
(along with some other types like float/int/etc., List<T> where T is serializable, and a few others)
every character has a diffrent attack so i need to add an interface to the player if this character is used
public class TestAttack : MonoBehaviour, IAttack
{
public void LeftClick()
{
Debug.Log("Left");
}
public void RightClick()
{
Debug.Log("Right");
}
}``` this is the interface im testing with
Use OnValidate to check if whatever was assigned to your field implements the interface and if it doesn't set it to null and throw error
You need to put ScriptableObject/MonoBehaviour as the type though
That's a class that implements an interface IAttack
this is IAttack:
public interface IAttack
{
void RightClick();
void LeftClick();
}```
You can't "add an interface", but you can add a component that implements that interface.
So are you trying to store the type of the interface in the ScriptableObject?
yeah i want to link an component that inpliments the class into the SO
yes but if i use IAttack as the type i cant add it in the editor
The component would only be a prefab though.. maybe the referenced object should also be an SO?
Or a regular class
You have a few options here.
You can make an abstract Attacker class that derives from MonoBehaviour
The player could then derive from Attacker
This starts causing problems when you want to have lots of different interfaces, though
i have just one interface
You can also split the "attacker" logic out from the player component and into a separate component.
One way is to make an enum in the SO and map that enum value to a type for the component to be added
So you'd have a Player component that has no idea about attacking itself
and then a separate component that, again, derives from an abstract class with the attack methods on it
This is what I've done in my game: lots of small modules
It's a composition-based approach.
can i somehow inspect this list as i could with a list of gameobjects
void AddOrRemoveSelectable(ISelect selectable)
{
//if its in the list remove it
if(selected.Contains(selectable))
{
Debug.Log("Removed Selectable");
RemoveSelectable(selectable);
}
else
{
Debug.Log("Added Selectable");
AddSelectable(selectable);
}
}``` im adding and removing, and debugging was a PITA
i remember something about serializeable , or maybe odin's free attribute asset thing, its on teh tip of my tongue and i cant think of it
There are several assets that let you serialize interface-typed fields.
notably, Odin Inspector can do that with one of its features, iirc
I've never used Odin, though.
It's private so it's not visible - relative to access modifiers.
yea, even when its public its not visible.
i just made it private b/c of that
and i was getting editor draw errors
yeah i have one attack script that does some checks if it passes it gets the component from the player that comes from IAttack and calls the func now i need to add the interface on the start dependeing on the scriptible objects on the player
Yeah, interfaces are not shown in the Unity inspector
first time ive used a list with something other than gameobject
If the player has a component that implements IAttack, then i'd just go ahead and turn IAttack into an abstract class
ive been spoiled by seeing the dropdown in teh inspector 😅
public abstract class Attack : MonoBehaviour
Since this derives from MonoBehaviour, Unity can serialize it.
Maybe reference a base class that's inherited and implements the Interface. You'd be able to show it's members.
It's a very annoying hangup. I wish there were some way to promise that I'm always going to be referencing a unity object.
Assuming there's a common base class
Yeah, so reference a list of type friendly selectable
It would then be available from the inspector
how can i link it in the so?
👍 i also have an NPC version
the scriptable object is an asset
i may use two lists.. with those specific types
Maybe have a base class called Selectable
assets can't reference scene objects
Where all types of selectable would inherit - it would dictate what's shown in the inspector
it would also not be useful to reference the Attack component on the player prefab
since that would always be the player prefab's Attack component
It sounds like the Player component should be able to tell you about its Attack component
@rocky canyon There's always the ugly hack of serializing it as Component and then casting it to your interface type when used
or maybe even components, if you have several attacks
hey, it's better than serializing a UnityEngine.Object
sometimes I click on a field of that type and I get hit by a massive wall of choices lol
every single asset in the entire project
i may do something temporary until i get the selection and deselection working.. currently its working but i gotta guess whats in the list (as i suspect)
list of a base class like u mention
i want to have var Attack in the so within the attack component is linked so i can add it
Okay, but what is that field going to store a reference to?
You could reference them as type GameObject and they'll be visible to the inspector
I hope interfaces become more inspector-friendly in the future. SerializeReference is dope but I want more
You "can" serialize an interface by serializing the MonoBehaviour directly. The downside is you have to cast the value (so you should probably cache it) in runtime.
interface IMyInterface {
void DoAction();
}
class MyImplementer : MonoBehaviour, IMyInterface { } //code etc..
class SomeReferenceThing : ScriptableObject {
public MonoBehaviour TheScript;
public IMyInterface Value => (IMyInterface)TheScript;
void OnValidate()
{
if (TheScript != null && TheScript is not IMyInterface)
{
Debug.LogError($"{script.GetType()} does not implement {nameof(IMyInterface)}!")
TheScript = null;
}
}
void Update()
{
Value.DoAction();
}
}```
Your scriptable object is an asset. It can't reference scene objects.
I don't understand your design.
I almost always have references to scriptable objects
scriptable objects don't have references to me
For plain C# classes you could also think about using a reflection-based approach by storing a string representation of the class and interface and then using the Activator class from the .NET framework to create instances when you need them.
Another downside to the method I linked is that the inspector will not filter your interface properly
this doesnt sound good
So you want a variable that dictates which Attack component is added to the character?
reflection is slow af ye
https://openupm.com/packages/net.tnrd.serializableinterface/ gives you a nice interface at least (ha-ha)
no i need it to add it to the player
Or referencing the base class (it doesn't need to inherit MB).
I'm guessing the Issue is that they don't have a base class.
ohh cool thx
You need what to add what to the player
I just said
added to the character
So I'm confused
Not the same thing though, one requires an implementation and the other is the abstraction
why isn't this built in..
class BaseClass1 : IMyInterface
class BaseClass2 : IMyInterface
Can't reference either which is why you want interface in the first place
Inheriting MB would require there to be an instance in the scene.. unless you're really wanting to make many prefabs.
each chracter has a scriptibleobject and you can choose one on the start in the so all stats for the character are saved and i need to add a script to handel the attacks but the gamobject stays the same for each character and movement just the attacks and model change
Yeah in this case it's a bit of a weird case as you typically want to ref an SO instead 😅
the so is refed on the player
you can put functions in ScriptableObjects too
how? so when i create one i can paste code into it?
A scriptableobject is a C# class and you can add methods and other functionality to it as you like
You just... type the code into the script
what is empty Vector3int is it equal to null?
Most of people use SO's as just data containers but they can also be instantiated and can have logic in them
it's not any different
I don't understand how this would help you "save stats"
value types cannot be null
default vector3int.zero
Default Vector3Int is (0,0,0)
scriptable objects are assets. the game can't modify them on disk.
these are the default stats how can i add code here
Changes will stick around in the editor for a bit
but that's not how it's going to work in the built game at all
thanks
It is a struct and all its member values will be their default. It has three ints and int's default is 0, so it is 0,0,0
surely you've written code in a MonoBehaviour before..
you don't shove the code into the inspector. you just..write it. in the class.
yes but i cant open this
Open the file, add code to it
Reference an SO that implements the wanted interface
The SO would implement the method and you'd get modular access to it by using your character stat this other SO
Open the script
the one that you made that defines this asset
not the asset itself
Hi, i have a problem when launching my C# code through Unity as it write : "No installed .NET SDK was found on the computer. If it is installed, make sure it can be found through the PATH environment variable. C# Dev Kit does not work without a supported version of SDK. After installing the SDK, you need restart the VS Code session, or the computer."
But i open it only with VSCode i don't have that
Like this:
public class GameAction : ScriptableObject {
public virtual void DoAction() { }
}
public class AttackAction : GameAction {
public float SomeValue;
public override void DoAction() {
Debug.Log("boom");
}
}
Someone have a solution ? (i'm on linux, I've installed Mono, .net, having this in my bashsrc : export PATH=$PATH:$HOME/dotnet)
but if i add it directly every instance i create from the so it will have the same code
You need to install .NET SDK
Just make more classes that implement the behaviour you care about
You can download with unity hub
what
Have many SOs.
For example: there may be different varieties of Character Stat SO and many varieties of an SO that inherit the base Ability SO where Character would reference the base Ability SO.
what distro are you using ? @errant spear
I have a video showing the whole config process on Linux Mint
How ? 'caus i already goes for Net sdk online and only find .NET that i already installed
this one
What's distro ? (not a native english speaker sorry)
you mean Ubuntu ?
Distribution of linux
are you using Ubunutu then?
yes
Press the Windows key and then look for System Settings.
Click System Settings, System tab.
Click Advanced system settings.
Click Environment Variables.
System variables can be set, find the PATH variable.
In the Variable Value field, add the directory path where the .NET SDK is installed. For example, if the .NET SDK is installed in C:\Program Files\dotnet\sdk\5.0.101, add the following to the Variable Value field:
C:\Program Files\dotnet\sdk\5.0.101
Click OK.
Close the system settings window. Then restart your pc
I have a video on the whole process
using Linux Mint
which is a Ubuntu distro
Im not using linux
Link to Unity hub Install
https://docs.unity3d.com/hub/manual/InstallHub.html#install-hub-linux
Link to VScode Download:
https://code.visualstudio.com/download
Link to .NET 7 SDK:
https://learn.microsoft.com/en-us/dotnet/core/install/linux-ubuntu-2210
or command
sudo apt-get update &&
sudo apt-get install -y dotnet-sdk-7.0
Time Stamps:
0...
no, you can download Visual Studio through the unity hub
i'll watch
sure! let me know if you encounter any issues
sorry for AI voice, i had no mic that week xD
At first i thought it was something else, yes sorry
if default value is 0,0,0
that why does this not even run
shouldnt the i be 0,0,0?
what if activeFires is empty?
Op is on Linux Visual Studio isn't a thing
the default value isn't in an empty list. nothing is in an empty list.
If nothing logs then either this code isn't running or activeFires is empty
Vector3Int myVec;
myVec can never be "empty". there's exactly one Vector3Int here, and it's stored in myVec. If you don't assign anything else to it, then myVec will store the default value.
List<Vector3Int> vectors = new();
vectors can contain zero, one, or many Vector3Int values.
I prepared such a spawn method, but I have a problem. For example, in the 3rd wave, there are only 3 a prefabs or 3 b prefabs. What should I do to make this happen randomly too? For example, in the 3rd wave, 2 prefabs A and 1 prefab B will be spawned randomly.
just pick randomEnemy inside the loop
yes I get that but should it run at least once as its not empty?
what if it is empty?
why do you think activeFires isn't empty?
it isnt enough
let me show
the current code is not enough, yes
but what it is when its empty how can I chceck that its empty
it picks randomEnemy once and then spawns that enemy many times
assuming that's a List<Vector3Int>, just do activeFires.Count == 0
that's why you need to pick randomEnemy every time the loop runs.
thanks that should do
Like this. İn the one wave, all enemys are same
How i can extend my code
Yes. Because you're picking randomEnemy only once.
i have EXACTLY done what the person does in the video and have this now
I wonder if your user or workspace settings are wrong.
ctrl-shift-P to open the command palette, then search for "JSON"
Open both of these and look at the config files.
how could i resolve this?
do i need to pick randomEnemy for each enemy?
Yes. Do you not understand what I'm talking about here?
you'd be looking for something like this
anything to do with "dotnet path"
im not native speaker sorry
did you restart pc after installing .net
and did you install it via the command line like the video ?
Oh true i forgot to restart i'll do that
erm...
int number = UnityEngine.Random.Range(0, 10);
for (int i = 0; i < 10; ++i)
{
Debug.Log(number);
}
vs.
for (int i = 0; i < 10; ++i)
{
int number = UnityEngine.Random.Range(0, 10);
Debug.Log(number);
}
Nothing in there.
that's my workspace json like you've asked
Now examine the user settings. There's probably more stuff in there.
thanks
I'd definitely do a restart before digging around any further, though!
do the easy step first
can you show which .net command you used to install
sudo apt-get update && sudo apt-get install -y dotnet-sdk-7.0
and did it say it installed ok , no errors?
this is french 🤷♂️
wait i'll trad it
don't need the whole log you can just tell me
$ sudo apt-get update && sudo apt-get install -y dotnet-sdk-7.0
[sudo] Student password:
Reached: 1 http://fr.archive.ubuntu.com/ubuntu jammy InRelease
Reached: 2 http://fr.archive.ubuntu.com/ubuntu jammy-updates InRelease
Reached: 3 https://download.mono-project.com/repo/ubuntu stable-focal InRelease
Reached: 4 http://security.ubuntu.com/ubuntu jammy-security InRelease
Reached: 5 http://fr.archive.ubuntu.com/ubuntu jammy-backports InRelease
Reached: 6 http://packages.microsoft.com/repos/code stable InRelease
Received from: 7 https://deb.nodesource.com/node_16.x jammy InRelease [4583 B]
Reached:9 https://packages.microsoft.com/ubuntu/20.04/prod focal InRelease
Reached: 8 https://hub-dist.unity3d.com/artifactory/hub-debian-prod-local stable InRelease
Reached: 10 https://download.sublimetext.com apt/stable/ InRelease
Reached: 11 https://paulcarroty.gitlab.io/vscodium-deb-rpm-repo/debs vscodium InRelease
4583 o received in 3s (1463 o/s)
Reading package lists... Done
N: The configured file “main/binary-i386/Packages” will not be considered because the repository “https://download.mono-project.com/repo/ubuntu stable-focal InRelease” does not support l “i386” architecture
W: https://download.sublimetext.com/apt/stable/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.
W: https://paulcarroty.gitlab.io/vscodium-deb-rpm-repo/debs/dists/vscodium/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.
Reading package lists... Done
Building the dependency tree... Done
Reading status information... Done
dotnet-sdk-7.0 is already the most recent version (7.0.405-1).
0 updated, 0 newly installed, 0 to remove and 8 not updated.
Archive of Ubuntu
I don't know what should be considered as an error so i prefer to give it like this
It sounds like the C# extension is looking in the wrong place.
ah, hm
weird, not even error if command is working or not..
or there are zero SDKs!
That's really strange
Yay :D
I bet that you got dotnet from one repository and the dotnet SDK from another repository.
Check this out
The fix is going to be to tell apt that you much prefer Microsoft's repository for anything dotnet related
(or to just remove the Microsoft package feed entirely)
i want the sine wave to be less apparent/weaker valleys n tops when coming closer to the player
nice code comments
i wish i knew where they come from
so t odo that i introduces the distance variable
and athe closer you are, the smaller the number after division becomes
which should make the waves less intense
time to take out your pen and paper
i can't find /etc
like through commands i have
but not manually
would create a 0 to 1 number based on distance, and multiply the sin by it
are you new to using linux?
Yes, for my studies i have a linux device
inverselerp can be used to take a range of distance and get your 0 to 1 multplier from it
so not everything is clear for me
could really just use an animation curve and multiply by that
and have more freedom on the editor vs hard coding values
That's the ticket.
for example...
float distanceFactor = Mathf.InverseLerp(5f, 20f, distance);
You could then plug this into an animation curve
float strength = curve.Evaluate(distanceFactor);
also speaking of animation curves is there a way to steal the animation curve from line renderer
that one is like extra polished
Rather, I want it because it clamps 0 to 1
If the bool manaOn == false it still runs and changes the material color. is this just bugged?
How do you know it's false?
set it to public and viewed in inspector
Well, it's definitely true if the code is occurring.
what is manaBlue? a reference to a material you assigned in the inspector?
yes
perhaps you have multiple objects using the material?
and multiple copies of this component in various places?
Maybe log thiscs Debug.Log($"Mana On: {manaOn}", this);
how is your reference to manaBlue created?
Assuming this isn't spamming the console, click the message when it's supposed to be false but not.
heelo
i was following a tutorial
Hoo boy, this was more of a challenge I wanted to do myself, was getting tight on time near the end.
I wanted to try to show how to setup something every game needs, a main menu, in as concise of a way as possible in a Unity Tutorial. I also tried to explain additional things like general UI advice in Unity, as well as Scene management (loadin...
So you do have many components of the same type.
as i was trying to make a fps
Click the message. What gets highlighted?
but something broke my game
Okay, now take that log and put it inside the if condition. Do you still see it printing false anywhere
i will send my project , can you guys help me with this one
fuck i cant send my project
what do i do
no one is going to review a whole project for you, break down the problem smaller and figure out what part is broken
describe what the issue is
Maybe just explain what's not working as expected and what step in the video you're at relative to time.
so a very important thing here is that you're referencing material assets
when you modify them, the changes will persist
you see unity changed since this video was made and im on the last steps of it
i cant add the start scripts to the main menu part , this is vital since it would make the whole thing work
if you are changing the material at runtime you will want to instead make a copy of the material then assing it to the renderer
also i think something is wron with the camera
I think you need to reference a renderer, and then do myRenderer.material.SetColor(...)
.material makes a copy of the material for the renderer if one doesn't already exist.
because its centered in the characters face
that way your modificitons will not effect multiple objects at once and they will not dirty the state of the mateirals in your assets folder
Are you sure you're not trying to place an instance from the scene onto the prefab? (assuming you're accidently looking at the prefab button)
what exacly do you mean im new to this
What time in the video are you unable to copy?
4:26
Can you show your hierarchy and that you've selected the three buttons?
sure just wait a second
I found a solution that works for me.. (only need it to debug at times)
NaughtyAttributes + Text Area
i casted them as Monobehaviours, then debug the names
https://assetstore.unity.com/packages/tools/utilities/serialize-interfaces-187505
i tried using this first, but i couldn't get the list to be visible, the closest i got was a drop down with broken elements inside, (just the menu bar and the three dots to drag around)
then i realized i hadn't imported naughtyattributes, and i love that asset, so i made it work w/ that instead with the little mini-debug-string-window
lol
I've tried some packages but I've just surrendered to not using interfaces this way
unity really needs editor support updates
ya, troublesome to say the least. there was a bug yesterday and i couldn't tell what was happening, so i wrote alot of debugs just to visualize what was happening
once i get the bugs worked out, i can get rid of this completely..
but swapping to interfaces really cleaned up my code, so im fine with them 🙂
went from something long and nasty like this
to a much more legible
if(!selected.Contains(selectable))
{
AddSelectable(selectable);
}
else
{
RemoveSelectable(selectable);
}
// first we need to know if this is already selected, if it is do the following
// we need to check if we start dragging
// if after so long our focused raycast position hasnt changed we can assume we want to open the units menu
// we also need to check if we're holding down
// if was a single quick click then we just need to deselect
// if it wasn't selected we can just assume we want to select it
}
else
{
// we clicked something that wasn't selectable
// are we selected?
// if we are what happens?
// if we're not what happens?
}``` still got a crazy interaction system to setup 😅
how to filter gameobjects in the scene based on components?
the whole scene?
ye
search using t:
or you mean code?
FindObjectsOfType
its kinda slow so you should prob not use it in something like Update
use awake/start to store them
no i mean like from the hierarchy
oh then what SteveSmith said
t:Collider
nice
if you were desperate why haven't you posted it yet ?
this is a code channel
lol
am pretty sure it has code involved
It's not, don't crosspost.
oh wait 2d lights doesnt have that
And if you think it's code related, then remove it from there and ask here with the code you're using for it.
You will be warned if you crosspost, your question is and belongs in #archived-lighting. Stop being a child.
is GetChild and Find("") the same performance?
doubtful.. GetChild is going to be constrained to just the parent and all its children
Find() is gonna search the entire Hierarchy
They probably meant this
https://docs.unity3d.com/ScriptReference/Transform.Find.html
Find is slower, as it has to compare strings
but I don't think it's going to be noticable unless you're doing it a lot
Get child acquires the object by index https://docs.unity3d.com/ScriptReference/Transform.GetChild.html
whereas Transform Find would search by string (it's name) https://docs.unity3d.com/ScriptReference/Transform.Find.html
Assuming you aren't referring to GameObject Find which searches the entire hierarchy.
Idk why but i get this error on VSC sometimes, but other times (like rn) the IDE does work, what is happening?
its faster to search thru a specific Parent
but i figured as much.. (very very little difference)
{
public CinemachineVirtualCamera VC;
public GameObject player;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Delay());
}
// Update is called once per frame
void Update()
{
}
private IEnumerator Delay()
{
yield return new WaitForSeconds(3.9f);
Vector3 deltaPos = player.transform.position - VC.transform.position;
float timePassed = 0;
while (timePassed < 1f)
{
timePassed += Time.deltaTime;
VC.transform.position += deltaPos * Time.deltaTime;
}
VC.transform.position = player.transform.position;
VC.Follow = player.transform;
}``` why is my VC not moving towards my player
What if you had 100 children? 
lol, not sure, i did use about 20- 30 children.. w/ alot nested
but 100s or 1000s idk 😄
If Unity uses a dictionary under the hood, it should be pretty quick with the hashing else if they're comparing names for a list... the number of elements might matter a lot.
Is this object destroyed or disabled after the coroutine starts
this was what i tested it on
no its active in the scene
with the highlighted one holding the Test script i was hunting for
however it is being used in a timeline
ahh, i used GetComponentInChildren not Find.
If it's already in a timeline why are you manually timing this
cause theres certain things with a virtual camera which u cant control in a timeline
Grand children do not seem to be evaluated. Good test either way 👍
oh cool, TIL
I don't know too much about Timeline but I'm pretty sure it's more than capable of affecting an object's position
i just dont ever wanna seach with strings anymore 😄
i try to avoid it lol i've even stopped using CompareTag()..
much prefer a TryGet and a component now
yeah but you cant set the follow target
i also dont know where the player is gonna be
Can't the timeline call functions in a script? You could put in a function that sets the follow
isnt the timeline like a glorified animator? couldn't u track the player thru a script, and maybe control that script via the timeline?
ya i was thinkin same as u
Seems like the issue is likely that the Timeline is overwriting the object's position, so this coroutine changes it, but the Timeline immediately changes it back
well i deleted the timeline and its still not moving
its just skipping to the position instantly
Try putting some logs in the coroutine, before and after the yield, inside the while, and after it
i have everything runs as it should
Then it would seem that something else is setting the transform
Phantom code
theres defitnly not
could it just be happening so quickly that it looks instant
Try logging the camera's position before the while, during the while, and after the while
Make sure to actually include which one is which
See if the position actually changes
it does
its just jumping from the start location to the end
not gradually changing over 1 second
like it shod
Oh, right, that's because you're doing it all in one frame
Your only wait is at the beginning
It does the rest instantly
Yes, that's why it runs instantly
Yes which is immediately
what it does all loops in one frame
Yes that's how all loops work
The only code that exists is that loop until it's finished
If you want to run one iteration and then wait a frame you should actually wait a frame
yield return null
but that at the end of the loop?
in the loop
after you do whatever you want the loop to do
You probably forgot to yield in the loop
that works cheers guys
{
yield return new WaitForSeconds(4f);
Vector3 deltaPos = player.transform.position - VC.transform.position;
float timePassed = 0;
while (timePassed < 1f)
{
timePassed += Time.deltaTime;
VC.transform.position += deltaPos * Time.deltaTime;
VC.transform.position = new Vector3(VC.transform.position.x, VC.transform.position.y, -35);
VC.m_Lens.OrthographicSize = -45 * Time.deltaTime;
yield return null;
}``` im trying to change the orthographic size as well now but thats not changing for some reason
Well, Time.deltaTime isn't likely to change much from frame to frame, so you're setting it to the same value every frame
Why are you trying to set the orthographic size to a constant times deltaTime anyway
You aren't decrementing it. You're setting it to negative forty five multiplied by whatever value delta time was that frame.
i want it to go from 50 to 5
and deltapos works in a similar way so i thought that would
So then why are you setting it to -45 divided by your framerate
... = 50 - 45 * an accumulating variable relative to time
perhaps you were looking for the += operator
oh it was meant to be =- 45
No it doesn't. You're adding a value to that. You're setting the orthographic size to a constant
i put a space on accident
That's the same thing you just typed
= - and =- are not different
what how the minus was connected to the 45 before and this time its on the equals making it a decrement
yeah
=- is not a thing. It's the same as = -. You are probably thinking of -=
can you invoke while passing a var?
No
Invoke must be given the name of a method to call.
It looks like you just want to call the method directly...
Use a coroutine instead
oh yeah
its still not changing tho
well, show us the code you wrote
{
yield return new WaitForSeconds(4f);
Vector3 deltaPos = player.transform.position - VC.transform.position;
float timePassed = 0;
while (timePassed < 1f)
{
timePassed += Time.deltaTime;
VC.transform.position += deltaPos * Time.deltaTime;
VC.transform.position = new Vector3(VC.transform.position.x, VC.transform.position.y, -35);
VC.m_Lens.OrthographicSize -= 45 * Time.deltaTime;
yield return null;
}```
what isn't changing?
VC.m_Lens.OrthographicSize
look in the inspector as the code runs. i see no reason for it to not go down over time
it just stays at 50
is the code even running?
and if so, does logging VC.m_Lens.OrthographicSize show the value is changing?
yeah its going down 0.4
i don't know how to interpret that. is it going down from 50 to 5, or is it just constnatly resetting to 50 and then getting reduced?
LensSettings is a struct.
You have to do this:
LensSettings lensSettings = VC.m_Lens;
lensSettings.OrthographicSize = -45 * Time.deltaTime;
VC.m_Lens = lensSettings;```
shouldn't that be a compile error?
One would expect so...
assuming that m_Lens is a property
but it isn't. it's a field
I see no problem with doing that.
is the camera actually in orthographic mode?
that didnt work
We need the response to this question #💻┃code-beginner message
from 50 to 5
So it's working 
This question is very important too @faint osprey
its a virtual camera so yes cause theres no other option
no
If it's a perspective camera you need FieldOfView not OrthographicSize
i thought u were asking what u want it to do
There are two options, orthographic or perspective (orthographic checkbox OFF is perspective)
i dont think there is
It looks like the code works in decreasing the value. The behavior just isn't what you're needing.
expand "Advanced"
By default, the virtual camera will use whatever mode the main camera is using
Okay, so it's set to force the main camera to be orthographic
does changing the ortho size actually do anything?
as in, just changing it by hand
yeah zooms in and out thats why i set it to 50 cause it was 5 but i want it to zoom in
I feel like you've got a second virtual camera that's following this virtual camera.
OrthographicSize doesn't seem to be a parameter you can manually change
that would neatly explain all of the behavior we've seen
no, you can. it controls how large the camera's sensor is
Oh okay
It's the height that the screen takes up in the game world
nope
well, it seems like changing the orthographic scale of the camera is doing nothing, so something is wrong.
I would verify that you're actually moving the camera you think you are:
Debug.Log("Moving", VC);
its changing just a very tiny amount
click on the log entry and make sure it selects the correct thing
so if you start the game and change the orthographic size, it works correctly (going from 50 to 5 makes you zoom in by 10x)
but if you let this coroutine change the orthographic size, the orthographic scale still drops from 50 to 5, but the camera barely zooms?
if i change it manually yes
Do you have any errors ?
Share the entire script.
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class SpawnCutsceneScriptCompanion : MonoBehaviour
{
public CinemachineVirtualCamera VC;
public GameObject player;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Delay());
}
// Update is called once per frame
void Update()
{
}
private IEnumerator Delay()
{
yield return new WaitForSeconds(4f);
Vector3 deltaPos = player.transform.position - VC.transform.position;
float timePassed = 0;
var lensSettings = VC.m_Lens;
while (timePassed < 1f)
{
timePassed += Time.deltaTime;
VC.transform.position += deltaPos * Time.deltaTime;
VC.transform.position = new Vector3(VC.transform.position.x, VC.transform.position.y, -35);
lensSettings.OrthographicSize -= 45 * Time.deltaTime;
yield return null;
}
VC.transform.position = player.transform.position;
VC.Follow = player.transform;
}
}
no
oh well that definitely isn't going to work now, since you aren't assigning lensSettings back into the camera
I wonder if this occurs whenever the field changes (via poll) or explicitly only when the vcam becomes live? It's obviously not a property.
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.1/api/Cinemachine.CinemachineVirtualCamera.html
but m_Lens is a struct
when you do var lensSettings = VC.m_Lens;, you copy the content of m_Lens in a local variable
These settings will be transferred to the Unity camera when vcam is live
I'm assuming once or would it do so constantly with a poll?
yes, which is why I said it wouldn't work above
VC.m_Lens = lensSettings; i added that after u said it
but its not working
it constantly updates
we need to rule out any really weird interference from any other code that we can't see.
Okay bcause you didn't write it in the above code
After the coroutine terminates, what is the orthographic size of the camera?
Remove that
Screenshot its inspector after the coroutine is done.
50 in editor but if i debug it its like 49.647
I thought you said it went down to 5.
So it doesn't go down to 5. It goes down to 49.647 and sits there.
no i said thats what i want it to do
Show me exactly what your code looks like right now.
So it didn't go down.
wait why
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class SpawnCutsceneScriptCompanion : MonoBehaviour
{
public CinemachineVirtualCamera VC;
public GameObject player;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Delay());
}
// Update is called once per frame
void Update()
{
}
private IEnumerator Delay()
{
yield return new WaitForSeconds(4f);
Vector3 deltaPos = player.transform.position - VC.transform.position;
float timePassed = 0;
var lensSettings = VC.m_Lens;
while (timePassed < 1f)
{
timePassed += Time.deltaTime;
VC.transform.position += deltaPos * Time.deltaTime;
VC.transform.position = new Vector3(VC.transform.position.x, VC.transform.position.y, -35);
lensSettings.OrthographicSize -= 45 * Time.deltaTime;
VC.m_Lens = lensSettings;
yield return null;
}
VC.transform.position = player.transform.position;
VC.Follow = player.transform;
}
}
where were you logging the orthographic size?
it's not in the code you just sent