0
votes
using UnityEngine;
using System.Collections;

public class MakeTwoPoints3D : MonoBehaviour {

    public GameObject cylinderPrefab;

    // Use this for initialization
    void Start () {

        CreateCylinderBetweenPoints(Vector3.zero, new Vector3(10, 10, 10), 0.5f);

    }

    void CreateCylinderBetweenPoints(Vector3 start, Vector3 end, float width)
    {
        var offset = end - start;
        var scale = new Vector3(width, offset.magnitude / 2.0f, width);
        var position = start + (offset / 2.0f);


        Object cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity);
        cylinder.transform.up = offset;
        cylinder.transform.localScale = scale;
    }

    // Update is called once per frame
    void Update () {

    }
}

On both lines same error:

cylinder.transform.up = offset;
cylinder.transform.localScale = scale;

Severity Code Description Project File Line Suppression State Error CS1061 'Object' does not contain a definition for 'transform' and no extension method 'transform' accepting a first argument of type 'Object' could be found (are you missing a using directive or an assembly reference?) MakeTwoPoints3D.cs 23 Active

1
Why are you declaring as Object? - SLaks
After reading here, I see you are instantiating based on the variable cylinderPrefab, and cylinderPrefab has type GameObject, so change the call to this: GameObject cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity) as GameObject; - Quantic

1 Answers

2
votes

Object is parent class of GameObject and GameObject as member of type Transform. If you try to access transform from an instance of Object class, it will show you following error:

Object' does not contain a definition for 'transform'

So accurate way of instantiating and using the resulted object as a GameObject is as Quantic said in comment :

GameObject cylinder = Instantiate(cylinderPrefab, position, Quaternion.identity) as GameObject;

OR

GameObject cylinder = (GameObject) Instantiate(cylinderPrefab, position, Quaternion.identity);

It is always to use null-check for safety before using the component in case of other types than GameObject. For example:

Rigidbody rb = Instantiate(somePrefab) as Rigidbody;
if(rb != null)
  // use it here

hope this helps.